Mode of Every Sliding Window

You are given an integer array nums of size n and an integer k.

For every contiguous subarray of size k, find its mode.

The mode of an array is the element that appears most frequently.

If multiple elements have the same highest frequency, choose the smallest among them.

Return an array containing the mode of each sliding window, from left to right.

Example 1:

Input: nums = [1, 2, 2, 3, 3], k = 3

Output: [2, 2, 3]

Explanation:

The windows of size 3 are:

  • [1, 2, 2] → frequency: 2 -> 2, 1 -> 1, so mode is 2
  • [2, 2, 3] → frequency: 2 -> 2, 3 -> 1, so mode is 2
  • [2, 3, 3] → frequency: 3 -> 2, 2 -> 1, so mode is 3

So, the answer is [2, 2, 3].

Example 2:

Input: nums = [4, 4, 1, 1, 2], k = 2

Output: [4, 1, 1, 1]

Explanation:

The windows of size 2 are:

  • [4, 4] → mode is 4
  • [4, 1] → both appear once, so choose the smaller one: 1
  • [1, 1] → mode is 1
  • [1, 2] → both appear once, so choose the smaller one: 1

So, the answer is [4, 1, 1, 1].

Now Your Turn!

Pick the correct output for the given input

Input: nums = [5, 2, 2, 7], k = 3

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= n <= 2 * 105
  • 1 <= nums[i] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> slidingWindowMode(vector<int>& nums, int k) {
// Your code goes here
}
};
Test Case

Input:

K
Nums