Final Prices With a Special Discount in a Shop (LeetCode 1475): Solution and Explanation

Easy
Array
Stack
Monotonic stack

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

  1. Copy prices into result and start with an empty stack of indices.
  2. For each index i: while the stack is not empty and prices[top] >= prices[i], pop top and subtract prices[i] from result[top].
  3. Push i; it now waits for its own discount.
  4. 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]
  1. Item 0 (8): nothing waits. Push 0. Stack prices: [8].
  2. Item 1 (4): 8 >= 4, so item 0 pays 8 - 4 = 4. Push 1. Stack: [4].
  3. Item 2 (6): 4 < 6, stop. Push 2. Stack: [4, 6].
  4. Item 3 (2): 6 >= 2, item 2 pays 4. 4 >= 2, item 1 pays 2. Push 3. Stack: [2].
  5. Item 4 (3): 2 < 3, stop. Push 4. Stack: [2, 3].
  6. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every index is pushed once and popped at most once, so the inner loop does O(n) work in total.

Space

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.