15% off all plans & roadmaps Use code
See plansFinal Prices With a Special Discount in a Shop
- LeetCode 1475
- Easy
- Stack Patterns
- Monotonic Stack
Updated
TL;DR: Each item gets the price of the first later item priced at or below it, subtracted from its own price. A monotonic stack of waiting indices finds every match in one left-to-right pass.
Problem
You get an integer array prices, where prices[i] is the price of item i in a shop.
The shop runs a special discount. If you buy item i, you receive a discount equal to prices[j]. Here j is the smallest index with j > i and prices[j] <= prices[i]. If no such index exists, you receive no discount.
Return an integer array answer, where answer[i] is the final price you pay for item i after its discount.
Example 1
Input: prices = [8,4,6,2,3] Output: [4,2,4,2,3] Explanation: Item 0 costs 8 and gets a discount of 4 from index 1, so you pay 4. Item 1 costs 4 and gets a discount of 2 from index 3, so you pay 2. Item 2 costs 6 and gets a discount of 2 from index 3, so you pay 4. Items 3 and 4 get no discount.
Example 2
Input: prices = [1,2,3,4,5] Output: [1,2,3,4,5] Explanation: No later price is at or below any item's price, so no discount applies.
Example 3
Input: prices = [10,1,1,6] Output: [9,0,1,6]
Constraints
1 <= prices.length <= 5001 <= prices[i] <= 1000
Constraints that matter
- With n up to 500, the brute force does at most 124,750 comparisons, so an O(n^2) scan is correct within the limits.
- Prices go up to 1000, but the algorithm never needs a table indexed by price. It only compares prices with each other.
- Each item needs its first later match, so the scan for an item must stop at the first hit and never be overwritten by a later one.
- Equal prices count as a discount (the test is less than or equal), so the stack pop test must include equality.
Hints
Hint 1
The rule asks for the first later item priced at or below the current one.
Hint 2
The beginner version asks the question for each item directly.
Solution
Intuition
The rule asks for the first later item priced at or below the current one. That is a next smaller or equal element question. When a problem asks for the nearest later element that satisfies a comparison, the usual tool is a monotonic stack, which is a stack whose contents stay in sorted order.
Picture a waiting line where each person holds a price tag and waits for a cheaper or equal tag to walk up. The stack is that waiting line, and each new price pays off the people at the front whose tags are at or above it.
Think of the stack as a waiting list. Each item waits until a later price at or below its own shows up. A new price can only discount waiting items priced at or above it. Keeping the list sorted by price puts those items on top, so the scan stops as soon as it reaches a waiting item cheaper than the new price.
Every item joins the list once and leaves at most once. That bounds the total work by the number of items, which is why one pass is enough.
Worked example
Input: prices = [7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7] Output: [1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7] Explanation: Items 0 through 5 each find a match one step to their right, with a discount of 1. Item 6 (price 1) has no later price at or below 1, so it keeps its price. Items 7 through 12 rise in price after their index, so none of them gets a discount.
Approach 1: Brute force
The beginner version asks the question for each item directly. Start at the item, read the items to its right in order, and stop at the first one priced at or below it. Subtract that price. If no later price matches, the item keeps its original price.
This version is correct. It does the same comparisons again and again, because every item rescans the right side from its own position.
Steps
- Copy
pricesintoanswer, so unmatched items keep their price. - For each index
ifrom 0 to n - 1, startjati + 1. - Compare
prices[j]withprices[i]for eachjin order. - On the first
jwithprices[j] <= prices[i], setanswer[i] = prices[i] - prices[j]and stop the inner loop. - Return
answer.
Dry run
Trace on the example [7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7].
For i = 0 (price 7), j = 1 has price 6, which is at most 7, so answer[0] becomes 1 after one comparison. Items 1 to 5 each match on their first comparison, so answer[1] through answer[5] become 1.
Item 6 (price 1) compares with prices 2 through 7 and finds no match. That is 6 comparisons, and answer[6] stays 1. Item 7 (price 2) compares with 3 through 7, with no match, which is 5 comparisons. Items 8 to 11 scan to the end without a match, and item 12 has nothing to scan.
The total is 27 comparisons. The final array is [1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7].
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) extra, apart from the output array |
Let n be the length of prices. The outer loop runs n times. For index i, the inner loop runs at most n - 1 - i times, so the total is at most n(n - 1) / 2 comparisons, which is O(n^2). The only other memory is a few counters, so the extra space is O(1).
PythonTested in our runner
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
n = len(prices)
answer = prices[:]
for i in range(n):
for j in range(i + 1, n):
if prices[j] <= prices[i]:
answer[i] = prices[i] - prices[j]
break
return answerThe Monotonic Stack infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Monotonic Stack
Part of Stack Patterns
Approach 2: One-pass monotonic stackOptimalMonotonic Stack
What's slow: the brute force rescans the right side for every item. In the example, prices 2 through 7 are read from many starting points, and most of those scans find nothing.
The insight that fixes it: an item needs checking only while it waits for a discount. Keep waiting items on a stack of indices. When a new price arrives, compare it with the top item. If the new price is at or below that item's price, pay the item off and check the next top.
The stack stays in increasing price order from bottom to top. A new index is pushed only after every higher-priced item above it is paid off. That order lets the loop stop early. If the new price is above the top, it is above every item below the top too.
Why it is correct. The stack always holds the indices that have not found a discount yet, sorted by price from bottom to top. Each popped item is matched by the first later price at or below it, since any earlier such price would have popped it already. Because the stack is sorted, a new price above the top is above everything below it, so stopping early loses nothing.
Steps
- Copy
pricesintoanswer, so unmatched items keep their price. - Create an empty stack for the indices of items still waiting for a discount.
- For each index
ifrom left to right, readprices[i]. - While the stack is not empty and
prices[i] <= prices[top], popidxand setanswer[idx] = prices[idx] - prices[i]. - Push
ionto the stack. This item now waits for a later discount. - Return
answer. Items still on the stack keep their original price.
Dry run
Each row shows the index, its price, the stack before the step, and the action. The stack holds indices, and their prices increase from bottom to top.
| i | price | stack before | action | answer change |
|---|---|---|---|---|
| 0 | 7 | [] | push 0 | none |
| 1 | 6 | [0] | pop 0 (7 - 6 = 1), push 1 | answer[0] = 1 |
| 2 | 5 | [1] | pop 1 (6 - 5 = 1), push 2 | answer[1] = 1 |
| 3 | 4 | [2] | pop 2 (5 - 4 = 1), push 3 | answer[2] = 1 |
| 4 | 3 | [3] | pop 3 (4 - 3 = 1), push 4 | answer[3] = 1 |
| 5 | 2 | [4] | pop 4 (3 - 2 = 1), push 5 | answer[4] = 1 |
| 6 | 1 | [5] | pop 5 (2 - 1 = 1), push 6 | answer[5] = 1 |
| 7 | 2 | [6] | 2 is above 1, push 7 | none |
| 8 | 3 | [6, 7] | 3 is above 2, push 8 | none |
| 9 | 4 | [6, 7, 8] | push 9 | none |
| 10 | 5 | [6, 7, 8, 9] | push 10 | none |
| 11 | 6 | [6, 7, 8, 9, 10] | push 11 | none |
| 12 | 7 | [6, 7, 8, 9, 10, 11] | push 12 | none |
After index 12, the stack holds [6, 7, 8, 9, 10, 11, 12]. Those items never found a discount, so they keep their prices. The final array is [1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7], which matches the example.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of prices. The loop body runs n times, and each index is pushed exactly once. Each index is popped at most once, so the pops total at most n, even though one iteration can pop several items. Each push and pop costs constant time, so the work is O(n), and the stack holds at most n indices, as on a strictly increasing array, so the extra space is O(n).
PythonTested in our runner
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
answer = prices[:]
stack = [] # indices of items still waiting for a discount
for i, price in enumerate(prices):
while stack and price <= prices[stack[-1]]:
idx = stack.pop()
answer[idx] = prices[idx] - price
stack.append(i)
return answerCommon mistakes
- Using
ifinstead ofwhilein the pop step. One price can discount several waiting items. For[3, 5, 4, 1], a singleifleaves index 0 unmatched and returns[3, 1, 3, 1]instead of[2, 1, 3, 1]. Replace theifwithwhile. - Using a strict test such as
prices[i] < prices[stack[-1]]. The problem counts equal prices as a discount. For[3, 3]the strict test returns[3, 3]instead of[0, 3]. Use<=. - Starting
answeras an array of zeros. An item with no later match must keep its full price. Copypricesintoanswerfirst, then overwrite only the matched items. - Pushing
prices[i]onto the stack instead ofi. The stack then loses the position, soanswer[idx]cannot be updated. Push the index, and readprices[idx]when you pop it. - Leaving out the
breakin the brute force inner loop. Without it,answer[i]takes the last match instead of the first. For[8, 4, 6, 2, 3], index 0 would become 8 - 3 = 5 instead of 4.
Edge cases
- A single item,
prices = [5]. No later index exists, so the output is[5]. - All values equal,
prices = [4, 4, 4]. Each item but the last takes a discount of 4 from its neighbour, giving[0, 0, 4]. - Strictly increasing values,
prices = [1, 2, 3, 4, 5]. No later price is at or below an earlier one, so the output equals the input and the stack keeps every index. - Strictly decreasing values,
prices = [5, 4, 3, 2, 1]. Each item takes a discount of 1 from the next item, so the output is[1, 1, 1, 1, 1]. - Maximum size, n = 500 with values up to 1000. The stack version does at most about 1000 pushes and pops, while the brute force can do about 124,750 comparisons.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Final Prices With a Special Discount in a Shop, with how to answer them.
Unlock the follow-upsFinal Prices With a Special Discount in a Shop FAQ
What is the time complexity of Final Prices With a Special Discount in a Shop?
The monotonic stack version runs in O(n) time, because each index is pushed once and popped at most once. The brute force scan runs in O(n^2) time, since each item may compare against every later item.
Why use a monotonic stack for Final Prices With a Special Discount in a Shop?
Each item waits until the first later price at or below it arrives. A stack keeps the waiting items ordered by price, so each new price only checks the top of the stack and the items it pays off. That turns the search into one pass.
Can Final Prices With a Special Discount in a Shop be solved in O(1) extra space?
Not with the stack approach, because the stack can hold all n indices, for example on a strictly increasing array. The brute force uses O(1) extra space but takes O(n^2) time. With n up to 500, the brute force is still correct within the limits.
Why does the pop condition use less than or equal instead of less than?
The problem counts a later price equal to the current price as a discount. For prices [3, 3] the answer is [0, 3]. A strict comparison would leave the first item at full price.
What does the stack hold in the Final Prices With a Special Discount in a Shop solution?
It holds the indices of items that have not yet found a discount. Their prices increase from bottom to top, so the top item is the first candidate that the current price is checked against.
Asked at
See which companies ask this — Pro
Related problems
- Next Greater Element I · same technique: Monotonic Stack
- Daily Temperatures · same technique: Monotonic Stack
- Car Fleet · same technique: Monotonic Stack
- Online Stock Span · same technique: Monotonic Stack
- Next Greater Element II · same technique: Monotonic Stack
- Valid Parentheses · same pattern: Stack Patterns
- Baseball Game · same pattern: Stack Patterns
- Crawler Log Folder · same pattern: Stack Patterns
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns