2288. Apply Discount to Prices LeetCode Solution

In this guide, you will get 2288. Apply Discount to Prices LeetCode Solution with the best time and space complexity. The solution to Apply Discount to Prices problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Apply Discount to Prices solution in C++
  4. Apply Discount to Prices solution in Java
  5. Apply Discount to Prices solution in Python
  6. Additional Resources
2288. Apply Discount to Prices LeetCode Solution image

Problem Statement of Apply Discount to Prices

A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign ‘$’. A word represents a price if it is a sequence of digits preceded by a dollar sign.

For example, “$100”, “$23”, and “$6” represent prices while “100”, “$”, and “$1e5” do not.

You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
Return a string representing the modified sentence.
Note that all prices will contain at most 10 digits.

Example 1:

Input: sentence = “there are $1 $2 and 5$ candies in the shop”, discount = 50
Output: “there are $0.50 $1.00 and 5$ candies in the shop”
Explanation:
The words which represent prices are “$1” and “$2”.
– A 50% discount on “$1” yields “$0.50”, so “$1” is replaced by “$0.50”.
– A 50% discount on “$2” yields “$1”. Since we need to have exactly 2 decimal places after a price, we replace “$2” with “$1.00”.

See also  3206. Alternating Groups I LeetCode Solution

Example 2:

Input: sentence = “1 2 $3 4 $5 $6 7 8$ $9 $10$”, discount = 100
Output: “1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$”
Explanation:
Applying a 100% discount on any price will result in 0.
The words representing prices are “$3”, “$5”, “$6”, and “$9”.
Each of them is replaced by “$0.00”.

Constraints:

1 <= sentence.length <= 105
sentence consists of lowercase English letters, digits, ' ', and '$'.
sentence does not have leading or trailing spaces.
All words in sentence are separated by a single space.
All prices will be positive numbers without leading zeros.
All prices will have at most 10 digits.
0 <= discount <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

2288. Apply Discount to Prices LeetCode Solution in C++

class Solution {
 public:
  string discountPrices(string sentence, int discount) {
    constexpr int kPrecision = 2;
    string ans;
    istringstream iss(sentence);

    for (string word; iss >> word;)
      if (word[0] == '$' && word.length() > 1) {
        const string digits = word.substr(1);
        if (ranges::all_of(digits,
                           [](const char digit) { return isdigit(digit); })) {
          const double val = stold(digits) * (100 - discount) / 100;
          const string s = to_string(val);
          const string trimmed = s.substr(0, s.find(".") + kPrecision + 1);
          ans += "$" + trimmed + " ";
        } else {
          ans += word + " ";
        }
      } else {
        ans += word + " ";
      }

    ans.pop_back();
    return ans;
  }
};
/* code provided by PROGIEZ */

2288. Apply Discount to Prices LeetCode Solution in Java

class Solution {
  public String discountPrices(String sentence, int discount) {
    final int kPrecision = 2;
    StringBuilder sb = new StringBuilder();

    for (final String word : sentence.split(" "))
      if (word.charAt(0) == '$' && word.length() > 1) {
        final String digits = word.substring(1);
        if (digits.chars().allMatch(c -> Character.isDigit(c))) {
          final double val = Double.parseDouble(digits) * (100 - discount) / 100;
          final String s = String.format("%.2f", val);
          final String trimmed = s.substring(0, s.indexOf(".") + kPrecision + 1);
          sb.append("$").append(trimmed).append(" ");
        } else {
          sb.append(word).append(" ");
        }
      } else {
        sb.append(word).append(" ");
      }

    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
  }
}
// code provided by PROGIEZ

2288. Apply Discount to Prices LeetCode Solution in Python

class Solution:
  def discountPrices(self, sentence: str, discount: int) -> str:
    kPrecision = 2
    ans = []

    for word in sentence.split():
      if word[0] == '$' and len(word) > 1:
        digits = word[1:]
        if all(digit.isdigit() for digit in digits):
          val = float(digits) * (100 - discount) / 100
          s = f'{val:.2f}'
          trimmed = s[:s.index('.') + kPrecision + 1]
          ans.append('$' + trimmed)
        else:
          ans.append(word)
      else:
        ans.append(word)

    return ' '.join(ans)
# code by PROGIEZ

Additional Resources

See also  2201. Count Artifacts That Can Be Extracted LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.