LeetCode Problem Workspace

Apply Discount to Prices

Apply Discount to Prices involves updating a sentence by applying a percentage discount to price words, with precise formatting.

category

1

Topics

code_blocks

5

Code langs

hub

3

Related

Practice Focus

Medium · String-driven solution strategy

bolt

Answer-first summary

Apply Discount to Prices involves updating a sentence by applying a percentage discount to price words, with precise formatting.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for String-driven solution strategy

Try AiBox Copilotarrow_forward

This problem requires applying a discount to prices embedded within a sentence. Each word that represents a price, indicated by a dollar sign, should be modified to reflect the discounted value, ensuring it has exactly two decimal places. The problem focuses on string-driven solutions and the proper handling of numeric formatting in string data.

Problem Statement

You are given a string sentence where each word is separated by spaces. Some of the words represent prices, indicated by a dollar sign ('$') followed by digits. Your task is to apply a discount to each price in the sentence based on the given percentage discount and return the updated sentence.

Prices in the sentence should be modified according to the discount, and all price updates should show exactly two decimal places. The updated sentence should reflect these changes while maintaining the format of other words.

Examples

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"

The words which represent prices are "1"and"1" and "2".

  • A 50% discount on "1"yields"1" yields "0.50", so "1"isreplacedby"1" is replaced by "0.50".
  • A 50% discount on "2"yields"2" yields "1". Since we need to have exactly 2 decimal places after a price, we replace "2"with"2" with "1.00".

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$"

Applying a 100% discount on any price will result in 0. The words representing prices are "3","3", "5", "6",and"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

Solution Approach

Identify Price Words

First, iterate through each word in the sentence. Check if it begins with a dollar sign ('$') and consists of digits following it. This identifies the words representing prices.

Apply Discount and Format

Once a price word is identified, apply the discount by calculating the new price. After calculating, format the result to two decimal places, ensuring that edge cases like 0.00 are handled properly.

Reconstruct the Sentence

After modifying all price words, rebuild the sentence by joining the words back together, ensuring proper spacing between them while preserving the structure of the original sentence.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

The time complexity is O(n) where n is the length of the sentence, as we need to iterate through each word. Space complexity is O(n) for storing the result sentence and intermediate transformations of the words.

What Interviewers Usually Probe

  • Can the candidate efficiently identify price words in a sentence?
  • Does the candidate apply the correct formatting to decimal numbers?
  • Does the candidate recognize edge cases such as 0% or 100% discounts?

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to handle the case where the discount is 0% or 100% correctly.
  • Not ensuring that prices are formatted to two decimal places, even when the result is a round number.
  • Misidentifying words that may contain a dollar sign but do not represent a price.

Follow-up variants

  • Implementing a solution that works for longer sentences with more words and prices.
  • Handling cases where there are no prices in the sentence.
  • Optimizing for larger inputs to handle edge cases like long strings efficiently.

FAQ

What is the primary challenge in the Apply Discount to Prices problem?

The main challenge is identifying price words and applying a discount to them while ensuring that the formatting remains consistent with exactly two decimal places.

How do I handle the discount percentage?

You calculate the new price by applying the discount percentage to the original price and ensuring the result is formatted to two decimal places.

Can a sentence have words that look like prices but are not?

Yes, only words that are preceded by a dollar sign and consist of digits should be treated as prices.

What if the discount is 0% or 100%?

For a 0% discount, prices remain unchanged. For a 100% discount, the price becomes 0.00.

How do I format the updated price correctly?

Ensure that each updated price has exactly two decimal places, even if the result is a whole number (e.g., 5becomes5 becomes 5.00).

terminal

Solution

Solution 1: Simulation

We can split the sentence into an array of words by spaces, then iterate through the array of words. For each word, if it represents a price, we update it to the price after applying the discount. Finally, we concatenate the updated array of words into a space-separated string.

1
2
3
4
5
6
7
8
class Solution:
    def discountPrices(self, sentence: str, discount: int) -> str:
        ans = []
        for w in sentence.split():
            if w[0] == '$' and w[1:].isdigit():
                w = f'${int(w[1:]) * (1 - discount / 100):.2f}'
            ans.append(w)
        return ' '.join(ans)
Apply Discount to Prices Solution: String-driven solution strategy | LeetCode #2288 Medium