Final Prices With a Special Discount in a Shop (LeetCode 1475): Solution and Explanation
Each item gets a discount equal to the price of the first later item that costs the same or less. Return what you pay for every item. For [8,4,6,2,3] the answer is [4,2,4,2,3].
Intuition
The discount for item i is the next element to its right that is less than or equal to it. This is the next smaller element problem in disguise.
Checking every later item for every item works for 500 prices, but it repeats the same comparisons many times.
Instead, scan left to right and keep the items that are still waiting for their discount on a stack. A new price settles every waiting item that costs at least as much, starting from the top. The items left behind are cheaper, so the stack's prices always increase from bottom to top.
Approach: Monotonic stack of waiting indices
- Copy
pricesintoresultand start with an empty stack of indices. - For each index
i: while the stack is not empty andprices[top] >= prices[i], poptopand subtractprices[i]fromresult[top]. - Push
i; it now waits for its own discount. - Indices left on the stack at the end never get a discount and keep their full price. Return
result.
Step-by-step example
prices = [8,4,6,2,3]
- Item 0 (8): nothing waits. Push 0. Stack prices: [8].
- Item 1 (4): 8 >= 4, so item 0 pays 8 - 4 = 4. Push 1. Stack: [4].
- Item 2 (6): 4 < 6, stop. Push 2. Stack: [4, 6].
- Item 3 (2): 6 >= 2, item 2 pays 4. 4 >= 2, item 1 pays 2. Push 3. Stack: [2].
- Item 4 (3): 2 < 3, stop. Push 4. Stack: [2, 3].
- Items 3 and 4 stay at full price. Answer: [4,2,4,2,3].
Code: Python, Java, C++
1class Solution:
2 def finalPrices(self, prices: List[int]) -> List[int]:
3 result = prices[:]
4 stack = [] # indices still waiting for a discount
5 for i, price in enumerate(prices):
6 while stack and prices[stack[-1]] >= price:
7 result[stack.pop()] -= price
8 stack.append(i)
9 return result1class Solution {
2 public int[] finalPrices(int[] prices) {
3 int[] result = prices.clone();
4 Deque<Integer> stack = new ArrayDeque<>();
5 for (int i = 0; i < prices.length; i++) {
6 while (!stack.isEmpty() && prices[stack.peek()] >= prices[i]) {
7 result[stack.pop()] -= prices[i];
8 }
9 stack.push(i);
10 }
11 return result;
12 }
13}1class Solution {
2public:
3 vector<int> finalPrices(vector<int>& prices) {
4 vector<int> result = prices;
5 vector<int> stack;
6 for (int i = 0; i < (int)prices.size(); i++) {
7 while (!stack.empty() && prices[stack.back()] >= prices[i]) {
8 result[stack.back()] -= prices[i];
9 stack.pop_back();
10 }
11 stack.push_back(i);
12 }
13 return result;
14 }
15};Time and space complexity
O(n)
Every index is pushed once and popped at most once, so the inner loop does O(n) work in total.
O(n)
When prices strictly increase, every index waits on the stack at the same time.
Other approaches
Brute force (time O(n^2), space O(1) extra)
For each item, scan forward until you find a price less than or equal to it and subtract it. Easy to write and fast enough for 500 items.
Common mistakes
- Using a strict
<comparison. An equal later price also counts as a discount, so[5,5]must give[0,5]. - Taking the smallest later price instead of the first one that qualifies. The discount comes from the nearest qualifying item.
- Popping only once per new item. One cheap item can settle several waiting items, so the pop has to be a loop.
Frequently asked questions
Why are the prices on the stack increasing from bottom to top?
Before pushing an item, the loop pops every waiting item that costs at least as much. Whatever remains below it is strictly cheaper, so the order is strictly increasing.
Why is the stack approach linear when it has a nested loop?
Each index is pushed exactly once and can be popped at most once. Across the whole scan the inner loop runs at most n times.
Which problems use the same pattern?
Daily Temperatures and Next Greater Element look for the next larger value with the same stack, just with the comparison flipped. Online Stock Span looks backwards with the same idea.