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 ProblemInput: "there are $1 $2 and 5$ candies", discount = 10Words: [there, are, $1, $2, and, 5$, candies]$1 → $0.90$2 → $1.805$ → 5$Valid PriceValid PriceInvalid FormatOutput: "there are $0.90 $1.80 and 5$ candies"Only valid prices ($1, $2) were transformed with 10% discount
Understanding the Visualization
1
Input
Sentence with mixed words and potential prices
2
Process
Identify valid prices and apply discount formula
3
Output
Transformed sentence with discounted prices
Key Takeaway
🎯 Key Insight: A valid price must start with $ and contain only digits after - apply discount formula and format to 2 decimal places
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