703036. Smallest sub-array with all occurences of most frequent element
Here is the detailed blog post:
Smallest sub-array with all occurrences of most frequent element
Summary
The problem is to find the smallest sub-array in a given array that contains all occurrences of the most frequent element. This problem involves arrays and data structures, and requires an algorithmic approach to solve.
Detailed Explanation
To solve this problem, we can start by finding the most frequent element in the array. We can use a hashmap to store the frequency of each element, and then find the maximum frequency. The smallest sub-array that contains all occurrences of the most frequent element will have at least as many elements as the maximum frequency.
Here's a step-by-step breakdown of the solution:
- Create a hashmap
freqto store the frequency of each element in the array. - Iterate through the array and update the
freqhashmap with the frequency of each element. - Find the maximum frequency
max_freqby iterating through the values in thefreqhashmap. - Initialize two pointers
startandendto 0, which will represent the start and end indices of the smallest sub-array. - Iterate through the array again, starting from the first element:
- If the current element's frequency is equal to
max_freq, move theendpointer to the right until we find an element with a frequency less thanmax_freq. - Once we've found an element with a frequency less than
max_freq, update thestartpointer to be the index of the previous element (i.e., the one before the current element).
- If the current element's frequency is equal to
- The smallest sub-array is the substring from
starttoend.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), since we only use a constant amount of space to store the hashmap and pointers.
Optimized Solutions
Here are optimized solutions in different programming languages:
Java
java
public int smallestSubArray(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
int maxFreq = Collections.max(freq.values());
int start = 0, end = 0;
for (int i = 0; i < arr.length; i++) {
if (freq.get(arr[i]) == maxFreq) {
while (i < arr.length - 1 && freq.get(arr[i + 1]) >= maxFreq) {
i++;
}
end = i;
start = i - (maxFreq - 1);
}
}
return arr.length > 0 ? end - start + 1 : 0;
}
Python
Not available