15% off all plans & roadmaps Use code

See plans

Final Prices With a Special Discount in a Shop

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 <= 500
  • 1 <= 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Copy prices into answer, so unmatched items keep their price.
  2. For each index i from 0 to n - 1, start j at i + 1.
  3. Compare prices[j] with prices[i] for each j in order.
  4. On the first j with prices[j] <= prices[i], set answer[i] = prices[i] - prices[j] and stop the inner loop.
  5. 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

TimeO(n^2)
SpaceO(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 answer

The 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 infographic

Solution 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

  1. Copy prices into answer, so unmatched items keep their price.
  2. Create an empty stack for the indices of items still waiting for a discount.
  3. For each index i from left to right, read prices[i].
  4. While the stack is not empty and prices[i] <= prices[top], pop idx and set answer[idx] = prices[idx] - prices[i].
  5. Push i onto the stack. This item now waits for a later discount.
  6. 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.

ipricestack beforeactionanswer change
07[]push 0none
16[0]pop 0 (7 - 6 = 1), push 1answer[0] = 1
25[1]pop 1 (6 - 5 = 1), push 2answer[1] = 1
34[2]pop 2 (5 - 4 = 1), push 3answer[2] = 1
43[3]pop 3 (4 - 3 = 1), push 4answer[3] = 1
52[4]pop 4 (3 - 2 = 1), push 5answer[4] = 1
61[5]pop 5 (2 - 1 = 1), push 6answer[5] = 1
72[6]2 is above 1, push 7none
83[6, 7]3 is above 2, push 8none
94[6, 7, 8]push 9none
105[6, 7, 8, 9]push 10none
116[6, 7, 8, 9, 10]push 11none
127[6, 7, 8, 9, 10, 11]push 12none

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

TimeO(n)
SpaceO(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 answer

Common mistakes

  • Using if instead of while in the pop step. One price can discount several waiting items. For [3, 5, 4, 1], a single if leaves index 0 unmatched and returns [3, 1, 3, 1] instead of [2, 1, 3, 1]. Replace the if with while.
  • 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 answer as an array of zeros. An item with no later match must keep its full price. Copy prices into answer first, then overwrite only the matched items.
  • Pushing prices[i] onto the stack instead of i. The stack then loses the position, so answer[idx] cannot be updated. Push the index, and read prices[idx] when you pop it.
  • Leaving out the break in 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-ups

Final 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

Practise it