Compute discounted prices in a queue
Company: Plaid
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in array processing, algorithm design, use of auxiliary data structures such as monotonic stacks, and formal complexity and correctness reasoning.
Constraints
- 0 <= len(prices) <= 200000
- 0 <= prices[i] <= 1000000000
Examples
Input: ([8, 4, 6, 2, 3],)
Expected Output: ([4, 2, 4, 2, 3], 8)
Explanation: Item 8 gets discount 4, item 4 gets discount 2, item 6 gets discount 2, and the last two items get no discount. Total savings are 4 + 2 + 2 = 8.
Input: ([1, 2, 3, 4, 5],)
Expected Output: ([1, 2, 3, 4, 5], 0)
Explanation: No item has a later price that is smaller than or equal to it, so no discounts apply.
Input: ([10, 1, 1, 6],)
Expected Output: ([9, 0, 1, 6], 2)
Explanation: 10 is discounted by the first 1, the second item 1 is discounted by the next 1, and the remaining two items receive no discount.
Input: ([5],)
Expected Output: ([5], 0)
Explanation: A single item has no later item, so it cannot receive a discount.
Input: ([],)
Expected Output: ([], 0)
Explanation: An empty list produces no final prices and no savings.
Solution
def solution(prices):
final_prices = prices[:]
total_savings = 0
stack = [] # indices waiting for their first qualifying discount
for i, price in enumerate(prices):
while stack and prices[stack[-1]] >= price:
idx = stack.pop()
final_prices[idx] = prices[idx] - price
total_savings += price
stack.append(i)
return final_prices, total_savingsTime complexity: O(n). Space complexity: O(n).
Hints
- As you scan from left to right, some earlier items are still waiting for the first later price that is smaller than or equal to them.
- A monotonic increasing stack of indices lets each item be pushed and popped at most once, which gives O(n) time.