Answer suffix maximum-frequency queries
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates algorithm design skills and array-processing competency for answering repeated queries efficiently, focusing on time and space complexity with large input sizes.
Constraints
- 0 <= n, m <= 200000
- If n == 0, then queries is empty
- 0 <= queries[k] < n for every query when n > 0
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([7, 5, 7, 2, 7], [0, 1, 2, 3, 4])
Expected Output: [3, 2, 2, 1, 1]
Explanation: The suffix maximum is 7 for every queried suffix, and its frequencies are 3, 2, 2, 1, and 1 respectively.
Input: ([4, 4, 4, 4], [0, 2, 3])
Expected Output: [4, 2, 1]
Explanation: Every suffix has maximum 4. In suffixes starting at indices 0, 2, and 3, it appears 4, 2, and 1 times.
Input: ([-3, -1, -1, -2], [0, 1, 2, 3])
Expected Output: [2, 2, 1, 1]
Explanation: Negative values are allowed. The suffix maximums are -1, -1, -1, and -2 with frequencies 2, 2, 1, and 1.
Input: ([9, 8, 7, 6], [0, 1, 3])
Expected Output: [1, 1, 1]
Explanation: In a strictly decreasing array, the first element of each suffix is the maximum and appears once.
Input: ([2, 1, 2, 3, 3], [1, 1, 4, 0])
Expected Output: [2, 2, 1, 2]
Explanation: Repeated queries should return the same result. The suffix starting at 1 has maximum 3 appearing twice, index 4 has only one 3, and index 0 also has maximum 3 appearing twice.
Input: ([1, 3, 2], [])
Expected Output: []
Explanation: If there are no queries, the answer is an empty list.
Hints
- Process the array from right to left. If you already know the suffix maximum and its count for `i+1`, you can update the answer for `i` using only `nums[i]`.
- Precompute an answer for every starting index once, then each query becomes a simple array lookup.