I just had an interview and was given this question:Given an array numbers, and a positive integer k, count the number of contiguous subarrays that contains at least k pairs of duplicatesThis is the solution I came up with which definitely misses some edge cases:
from collections import Counterdef solution(numbers, k): # for a subarray to contain at least k pairs of duplicates the subarray must be at least size 2k start, count, array_count = 0, 0, 0 window_size = 2*k freq_map = Counter(numbers[:window_size]) # check if in the initial window, any element has a freq greater than 1 for _, frequency in freq_map.items(): if frequency > 1: count += 1 for num in numbers[window_size:]: freq_map[num] += 1 if freq_map[num] >= 2: count += 1 if count >= k: array_count += 1 if freq_map[numbers[start]]: freq_map[numbers[start]] -= 1 if freq_map[numbers[start]] < 2: count -= 1 start += 1 # slide starting point of window return array_count
Truth is I think I satisfy all test cases except when the entire array is included in the result. Which makes me believe the optimum solution is not a sliding window solution. Such as numbers = [2,2,2,2,2,2] k = 3
or numbers = [0,1,0,1,0] k = 2
I also know I miss the case where a valid subarray could exist in the initial window.
I would love to see more optimum solutions please so I can learn (preferably if it can be solved with a sliding window lol).
To make everything crystal clear, the interviewer was expecting the answer for [2,2,2,2,2,2] k=3
to be 1 since there is only 1 subarray which has at least 3 pairs of duplicates(2's) `