703036. Smallest sub-array with all occurences of most frequent element

Easy

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:

  1. Create a hashmap freq to store the frequency of each element in the array.
  2. Iterate through the array and update the freq hashmap with the frequency of each element.
  3. Find the maximum frequency max_freq by iterating through the values in the freq hashmap.
  4. Initialize two pointers start and end to 0, which will represent the start and end indices of the smallest sub-array.
  5. Iterate through the array again, starting from the first element:
    • If the current element's frequency is equal to max_freq, move the end pointer to the right until we find an element with a frequency less than max_freq.
    • Once we've found an element with a frequency less than max_freq, update the start pointer to be the index of the previous element (i.e., the one before the current element).
  6. The smallest sub-array is the substring from start to end.

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

View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.