Compute discounted prices and full-price indices
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates array-processing skills, competency with next-smaller-or-equal element patterns, and the ability to compute aggregated results under ordering constraints.
Constraints
- 0 <= n <= 2 * 10^5
- len(prices) == n
- 0 <= prices[i] <= 10^9
- Use a 64-bit integer type for the total in languages with fixed-size integers
Examples
Input: (3, [5, 1, 3])
Expected Output: (8, [1, 2])
Explanation: Item 0 is discounted by prices[1] = 1, so its final price is 4. Items 1 and 2 have no qualifying item to their right, so they are sold at full price. Total = 4 + 1 + 3 = 8.
Input: (5, [8, 4, 6, 2, 3])
Expected Output: (15, [3, 4])
Explanation: Final prices are [4, 2, 4, 2, 3]. Items at indices 3 and 4 have no smaller-or-equal item to their right.
Input: (4, [5, 5, 5, 5])
Expected Output: (5, [3])
Explanation: Each of the first three items is discounted by the next 5, so their final prices are 0. The last item has no discount and remains 5.
Input: (4, [1, 2, 3, 4])
Expected Output: (10, [0, 1, 2, 3])
Explanation: No item has a smaller-or-equal value to its right, so every item is sold at full price.
Input: (1, [7])
Expected Output: (7, [0])
Explanation: With only one item, there is nothing to the right, so it is sold at full price.
Input: (0, [])
Expected Output: (0, [])
Explanation: There are no items, so the total is 0 and there are no full-price indices.
Hints
- Try scanning from left to right while keeping track of earlier items that still have not found a discount.
- If the current price is less than or equal to some previous prices, it becomes the first valid discount for those previous items.