Apply Discount to Prices - Problem

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: All prices will contain at most 10 digits.

Input & Output

Example 1 — Basic Case
$ Input: sentence = "there are $1 $2 and 5$ candies", discount = 10
Output: "there are $0.90 $1.80 and 5$ candies"
💡 Note: $1 becomes $0.90 (90% of $1), $2 becomes $1.80 (90% of $2). 5$ is invalid ($ at end) so unchanged.
Example 2 — No Valid Prices
$ Input: sentence = "1 2 3 4 5 6 7 8 9 10", discount = 50
Output: "1 2 3 4 5 6 7 8 9 10"
💡 Note: No words start with $, so sentence remains unchanged.
Example 3 — Edge Cases
$ Input: sentence = "$ $1e5 $100", discount = 20
Output: "$ $1e5 $80.00"
💡 Note: $ (only $) and $1e5 (contains 'e') are invalid. Only $100 → $80.00 (80% of $100).

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
  • 0 ≤ discount ≤ 100

Visualization

Tap to expand
Apply Discount to Prices INPUT Sentence (words): there are $1 $2 and 5$ candies = Valid price Discount: 10% Valid Price Pattern: $[digits only] 5$ is NOT valid ($ not first) $1e5 is NOT valid (has 'e') ALGORITHM STEPS 1 Split Sentence Split by spaces into words 2 Check Each Word Is it a valid price? 3 Apply Discount price * (100-discount)/100 4 Format Result Exactly 2 decimal places Example Calculations: $1 --> 1 * 0.90 = 0.90 --> "$0.90" $2 --> 2 * 0.90 = 1.80 --> "$1.80" FINAL RESULT Modified Sentence: there are $0.90 $1.80 and 5$ candies = Discounted price Output String: "there are $0.90 $1.80 and 5$ candies" OK - Complete! 2 prices updated 5$ unchanged (invalid) Key Insight: A valid price must start with '$' followed by ONLY digits. Words like "5$" or "$1e5" are NOT valid prices. Use regex or manual parsing to validate, then apply the formula: new_price = original_price * (100 - discount) / 100, formatted to exactly 2 decimals. TutorialsPoint - Apply Discount to Prices | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
32.3K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen