#2288

Apply Discount to Prices

Medium
StringString ManipulationRegular Expressions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a single pass through the sentence to identify and update prices efficiently. This reduces the time complexity significantly while maintaining clarity in the code.

⚙️

Algorithm

6 steps
  1. 1Step 1: Split the sentence into words using space as a delimiter.
  2. 2Step 2: Initialize an empty list to store the modified words.
  3. 3Step 3: For each word, check if it starts with '$' and is followed by digits.
  4. 4Step 4: If it is a price, convert the price to a float, apply the discount, format it to two decimal places, and append it to the list.
  5. 5Step 5: If it is not a price, append the word unchanged.
  6. 6Step 6: Join the modified words back into a single string and return it.
solution.py15 lines
1# Full working Python code
2sentence = 'there are $1 $2 and 5$ candies in the shop'
3discount = 50
4
5words = sentence.split()
6modified_words = []
7for word in words:
8    if word.startswith('$') and word[1:].isdigit():
9        price = float(word[1:])
10        discounted_price = price * (1 - discount / 100)
11        modified_words.append(f'${discounted_price:.2f}')
12    else:
13        modified_words.append(word)
14result = ' '.join(modified_words)
15print(result)

Complexity note: The time complexity is O(n) because we traverse the sentence once, processing each word in constant time. The space complexity is O(n) due to storing the modified words in a new list.

  • 1Identifying valid prices requires checking the format of each word.
  • 2Formatting numbers to two decimal places is crucial for price representation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.