Magicsheet logo

Apply Discount to Prices

Medium
37.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Apply Discount to Prices

What is this problem about?

The "Apply Discount to Prices interview question" is a string parsing and formatting challenge. You are given a sentence containing words and prices (represented as a '$' followed by a number). Your task is to find all valid prices and reduce them by a given percentage. The final sentence must be returned with the discounted prices formatted to exactly two decimal places.

Why is this asked in interviews?

Amazon uses the "Apply Discount to Prices coding problem" to test a candidate's string manipulation skills and attention to detail. It requires identifying what constitutes a "valid price" (it must be a stand-alone word like $100, not part of another word like abc$100) and handling floating-point precision for the output.

Algorithmic pattern used

This problem follows the String Tokenization and Validation pattern.

  1. Split: Break the sentence into words using spaces as delimiters.
  2. Identify: For each word, check if it starts with '$' and if the remaining characters are purely numeric (representing a positive integer).
  3. Calculate: If valid, convert the numeric part to a double, apply the discount (Priceimes(1discount100))(Price imes (1 - \frac{discount}{100})).
  4. Format: Convert the discounted price back to a string with two decimal places.
  5. Join: Combine all words back into a single sentence.

Example explanation

Sentence: "there are $100 and $50 items", Discount: 10%

  • Word "100":Validprice.Discounted:100": Valid price. Discounted: 90.00.
  • Word "and": Not a price.
  • Word "50":Validprice.Discounted:50": Valid price. Discounted: 45.00. Result: "there are $90.00 and $45.00 items"

Common mistakes candidates make

  • Regex errors: Using a regex that incorrectly identifies $100abc as a price. A price must be a separate word.
  • Floating point precision: Using default string conversion instead of a formatter like %.2f or toFixed(2), leading to answers like $90.1 instead of $90.10.
  • **Empty ':Treatingasingle"':** Treating a single "" character as a valid price.

Interview preparation tip

Get comfortable with your language's string formatting and tokenization tools. In an interview, being able to quickly split a string and validate parts using built-in methods (like isdigit() or parseFloat) saves valuable time.

Similar Questions