EasyNo. 1475

Final Prices With a Special Discount in a Shop — LeetCode 1475 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic Stack
Reading time
2 min

The problem

You are given an integer array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop.

Example

Input
prices = [8,4,6,2,3]
Output
[4,2,4,2,3]
Explanation
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.

Python solution

PythonSolution
class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        stk = []
        for i in reversed(range(len(prices))):
            x = prices[i]
            while stk and x < stk[-1]:
                stk.pop()
            if stk:
                prices[i] -= stk[-1]
            stk.append(x)
        return prices

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1475. Final Prices With a Special Discount in a Shop is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium
0853Car FleetMedium

Frequently asked questions

How hard is LeetCode 1475. Final Prices With a Special Discount in a Shop?

LeetCode 1475. Final Prices With a Special Discount in a Shop is rated Easy on LeetCode.

What is the time complexity of LeetCode 1475. Final Prices With a Special Discount in a Shop?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1475. Final Prices With a Special Discount in a Shop?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1475. Final Prices With a Special Discount in a Shop cover?

LeetCode 1475. Final Prices With a Special Discount in a Shop is tagged Stack, Array and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.