We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Apply Discount to Prices

Number: 2373

Difficulty: Medium

Paid? No

Companies: Amazon


Problem Description

A sentence is a string of single-space separated words where each word can include digits, lowercase letters, and the dollar sign. A word represents a price if it starts with a dollar sign followed by a sequence of digits. Given a sentence and a discount percentage, the task is to apply the discount to every valid price, update it to exactly two decimal places, and return the modified sentence.


Key Insights

  • Identify words that start with '$' and contain only digits afterwards.
  • Extract the numeric value from valid price words.
  • Apply the discount using the formula: discounted_price = price * (100 - discount) / 100.
  • Format the discounted price to exactly two decimal places.
  • Reconstruct the sentence with the updated prices.

Space and Time Complexity

Time Complexity: O(n), where n is the number of characters in the sentence. Space Complexity: O(n), as we store the split words and the final sentence.


Solution

The solution involves splitting the sentence into words, then checking each word to see if it represents a valid price. For a valid price (i.e., it begins with '$' and the remainder consists solely of digits), extract the number, apply the discount, and format the result with exactly two decimal places. Finally, reassemble the words into the final sentence. This approach uses simple string manipulation combined with arithmetic operations and formatting functions.


Code Solutions

# Function to apply discount on valid price words in a sentence
def applyDiscount(sentence, discount):
    # Split the sentence into words
    words = sentence.split(" ")
    discount_multiplier = (100 - discount) / 100.0
    result = []
    
    # Process each word
    for word in words:
        # Check if the word starts with '$' and remaining characters are digits
        if word.startswith("$") and word[1:].isdigit():
            # Convert the numeric part to a float
            price = float(word[1:])
            # Apply the discount
            discounted_price = price * discount_multiplier
            # Format the discounted price with exactly two decimals
            formatted_price = "${:.2f}".format(discounted_price)
            result.append(formatted_price)
        else:
            result.append(word)
    
    # Join the processed words back into a sentence
    return " ".join(result)

# Example usage:
sentence = "there are $1 $2 and 5$ candies in the shop"
discount = 50
print(applyDiscount(sentence, discount))
← Back to All Questions