File: final-prices-with-a-special-discount-in-a-shop/solution.py

Date: 2026-06-06

Time: 16:31

Final Prices with a Special Discount in a Shop

Purpose

This file solves LeetCode 1475. Given a list of prices, for each item i, find the first item j > i where prices[j] <= prices[i], and subtract prices[j] as a discount. If no such j exists, the price stays unchanged.

The file owns exactly one responsibility: the finalPrices method on the Solution class.

Key Components

Solution.finalPrices(prices: List[int]) -> List[int] — Takes a price list, returns a new list with discounts applied. Does not mutate the input (operates on prices[:]).

Patterns

This is a monotone stack solution — the classic pattern for "find the next smaller or equal element" problems. The stack holds indices of items still waiting for their discount. When a new price is small enough to serve as a discount for items on the stack, those items get popped and resolved.

The stack maintains a strictly increasing invariant on the prices it references: prices[stack[0]] < prices[stack[1]] < ... < prices[stack[-1]]. The while condition prices[stack[-1]] >= price pops everything that the current price can discount, preserving this invariant after the append.

Dependencies

Flow

1. Copy prices into result so the input isn't mutated.

2. Initialize an empty stack of indices.

3. Iterate through prices left to right. For each (i, price):

4. Indices remaining on the stack never found a discount — they keep their original price (already correct in result from the copy).

5. Return result.

Invariants

Error Handling

None. The method assumes valid input per LeetCode constraints (non-empty list of positive integers). No bounds checking, no exception handling.

Topics to Explore

Beliefs