Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.
"$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
Return a string representing the modified sentence.
Note that all prices will contain at most 10 digits.
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" Explanation: The words which represent prices are "$1" and "$2". - A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50". - A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$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$" Explanation: Applying a 100% discount on any price will result in 0. The words representing prices are "$3", "$5", "$6", and "$9". Each of them is replaced by "$0.00".
Constraints:
1 <= sentence.length <= 105sentence consists of lowercase English letters, digits, ' ', and '$'.sentence does not have leading or trailing spaces.sentence are separated by a single space.10 digits.0 <= discount <= 100Problem summary: A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign. For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not. You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence. Note that all prices will contain at most 10 digits.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"there are $1 $2 and 5$ candies in the shop" 50
"1 2 $3 4 $5 $6 7 8$ $9 $10$" 100
multiply-strings)apply-discount-every-n-orders)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2288: Apply Discount to Prices
class Solution {
public String discountPrices(String sentence, int discount) {
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; ++i) {
if (check(words[i])) {
double t = Long.parseLong(words[i].substring(1)) * (1 - discount / 100.0);
words[i] = String.format("$%.2f", t);
}
}
return String.join(" ", words);
}
private boolean check(String s) {
if (s.charAt(0) != '$' || s.length() == 1) {
return false;
}
for (int i = 1; i < s.length(); ++i) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
}
// Accepted solution for LeetCode #2288: Apply Discount to Prices
func discountPrices(sentence string, discount int) string {
words := strings.Split(sentence, " ")
for i, w := range words {
if w[0] == '$' {
if v, err := strconv.Atoi(w[1:]); err == nil {
words[i] = fmt.Sprintf("$%.2f", float64(v*(100-discount))/100)
}
}
}
return strings.Join(words, " ")
}
# Accepted solution for LeetCode #2288: Apply Discount to Prices
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)
// Accepted solution for LeetCode #2288: Apply Discount to Prices
/**
* [2288] Apply Discount to Prices
*
* A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.
*
* For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not.
*
* You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
* Return a string representing the modified sentence.
* Note that all prices will contain at most 10 digits.
*
* 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"
* Explanation:
* The words which represent prices are "$1" and "$2".
* - A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".
* - A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$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$"
* Explanation:
* Applying a 100% discount on any price will result in 0.
* The words representing prices are "$3", "$5", "$6", and "$9".
* Each of them is replaced by "$0.00".
*
*
* Constraints:
*
* 1 <= sentence.length <= 10^5
* 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
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/apply-discount-to-prices/
// discuss: https://leetcode.com/problems/apply-discount-to-prices/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn discount_prices(sentence: String, discount: i32) -> String {
let mut result = sentence.split(' ').fold(String::from(""), |acc, s| {
format!(
"{}{} ",
acc,
if s.chars().next() == Some('$') {
if let Ok(price) = &s[1..].parse::<f64>() {
format!("${:.2}", price * (1.0 - (discount as f64) / 100.0))
} else {
s.to_string()
}
} else {
s.to_string()
}
)
});
result.pop();
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2288_example_1() {
let sentence = "there are $1 $2 and 5$ candies in the shop".to_string();
let discount = 50;
let result = "there are $0.50 $1.00 and 5$ candies in the shop".to_string();
assert_eq!(Solution::discount_prices(sentence, discount), result);
}
#[test]
fn test_2288_example_2() {
let sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$".to_string();
let discount = 100;
let result = "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$".to_string();
assert_eq!(Solution::discount_prices(sentence, discount), result);
}
}
// Accepted solution for LeetCode #2288: Apply Discount to Prices
function discountPrices(sentence: string, discount: number): string {
const sell = (100 - discount) / 100;
const reg = new RegExp(/^(\$)(([1-9]\d*\.?\d*)|(0\.\d*))$/g);
const words = sentence.split(' ').map(d => {
if (!reg.test(d)) return d;
return d.replace(reg, (s, $1, $2) => {
return `$${(sell * $2).toFixed(2)}`;
});
});
return words.join(' ');
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.