Square | Phonic | Find the mode in the window of numbers
Anonymous User
1765

Finding mode for every window of size k in an array

Given an array of size n and k, how do you find the mode for every contiguous subarray of size k?

For example

arr = 1 2 2 6 6 1 1 7 
k = 3 
ans = 2 2 6 6 1 1

I was thinking of having a hashmap where the key is no and value is frequency, treemap where the key is freq and value is number, and having a queue to remove the first element when the size > k. Here the time complexity is o(nlog(n)). Can we do this in O(1)?.

This question was aked in Square.

Comments (7)