Compute final prices with next smaller discount
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: This question evaluates array-processing and algorithmic problem-solving skills, focusing on reasoning about subsequent elements to compute element-wise discounts under input constraints.
Constraints
- 1 <= len(prices) <= 200000
- 1 <= prices[i] <= 1000000000
Examples
Input: ([8, 4, 6, 2, 3],)
Expected Output: [4, 2, 4, 2, 3]
Explanation: Item 0 gets discount 4, item 1 gets discount 2, item 2 gets discount 2, and the last two items have no later smaller-or-equal discount.
Input: ([1],)
Expected Output: [1]
Explanation: A single item has no later item to provide a discount.
Hints
- A brute-force search for each item would be too slow for large inputs. Think about how to remember items that are still waiting for a discount.
- Use a monotonic stack of indices. When the current price is less than or equal to the price at the top index, it can serve as that item's discount.