The Final Prices With a Special Discount interview question asks you to calculate the final price of items after applying a specific discount rule. For each item at price prices[i], you receive a discount equal to the price of the first item to its right () such that prices[j] <= prices[i]. If no such item exists, you pay the full price.
Companies like Uber and Amazon use this Monotonic Stack interview pattern to test your efficiency with linear data. It’s a "Next Smaller Element" variation. While an O(N^2) solution using nested loops is easy to write, the interviewer expects the O(N) stack-based solution, which demonstrates a more advanced understanding of data structures.
This problem is solved using a Monotonic Increasing Stack.
prices[i]:
prices[i]:
i is the "first smaller or equal" item for the item at the top of the stack.prices[stack.pop()] -= prices[i].i onto the stack.Prices: [8, 4, 6, 2, 3]
[0].4 <= 8. Discount for 8 is 4. 8 - 4 = 4. Stack [1].6 > 4. Stack [1, 2].2 <= 6. Discount for 6 is 2. 6 - 2 = 4.2 <= 4. Discount for 4 is 2. 4 - 2 = 2.[3].3 > 2. Stack [3, 4].
Final: [4, 2, 4, 2, 3]."Next Smaller/Greater Element" is a very common interview theme. Whenever you need to look for the first element to the right that satisfies a comparison, a Monotonic Stack is the optimal solution.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Buildings With an Ocean View | Medium | Solve | |
| Next Greater Element II | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve | |
| Count Bowl Subarrays | Medium | Solve | |
| Maximal Range That Each Element Is Maximum in It | Medium | Solve |