Ctrl K

Discounted Price Tags

Medium
The string text is a list of words separated by single spaces. Words are made of lowercase English letters, digits and the $ sign. A word is a **price** if it is a $ followed only by digits (at least one): "$15" is a price, while "15", "$", "$1x" and "$15$" are not. The shop is having a sale: every price drops by percent percent. Replace each price with the new one written with exactly two digits after the decimal point (for example "$7.50" or "$3.00"), leave all other words alone, and return the resulting string.
Example 1
text="lamp $40 and bulbs $3 each", percent=25 → 'lamp $30.00 and bulbs $2.25 each'

The prices are "$40" and "$3". At 25% off they become "$30.00" and "$2.25".

Example 2
text="$7 7$ $7$ $ $x7 $7", percent=10 → '$6.30 7$ $7$ $ $x7 $6.30'

Only the two "$7" words are prices; each turns into "$6.30". "7$", "$7$", "$" and "$x7" are not prices and stay as they are.

Example 3
text="free shipping", percent=50 → 'free shipping'

There are no prices, so the text is unchanged.

Constraints
  • 1 ≤ len(text) ≤ 10⁵
  • text contains lowercase English letters, digits, spaces and $
  • No leading or trailing spaces; words are separated by exactly one space
  • Every price is a positive number with no leading zeros and at most 10 digits
  • 0 ≤ percent ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Repeat-Free Stretch MediumLongest Mirror Fragment MediumReading a Zigzag by Rows MediumLenient Number Reader MediumNumber in Roman Numerals Medium
loading Python…
Input
text="lamp $40 and bulbs $3 each", percent=25
Expected
'lamp $30.00 and bulbs $2.25 each'

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.