703845. Sub-arrays with equal number of occurences
Hard
Sub-arrays with equal number of occurrences
Summary
The problem involves finding all sub-arrays in a given array that have an equal number of occurrences. This means, for each pair of elements in the array, you need to find all sub-arrays where these two elements appear equally many times.
Detailed Explanation
To solve this problem, we can use a combination of frequency arrays and sliding window techniques. Here's a step-by-step breakdown:
- Initialize an empty hash map
freqMapto store the frequency of each element in the array. - Iterate through the array using two pointers,
startandend, which represent the start and end indices of the current sub-array. - For each element at index
i, increment its count infreqMap. - Calculate the frequency of the current sub-array by subtracting the counts of elements to the left of
startfrom the total count. - If the frequency is equal to 0, it means all elements up to this point have been seen equally many times. Update the result with the current sub-array.
- Slide the window by incrementing
endand decrementingstartuntilendreaches the end of the array. - Repeat steps 3-6 for each element in the array.
Time complexity: O(n^2), where n is the length of the array, because we're iterating through the array with two pointers. Space complexity: O(n), as we need to store the frequency map and result arrays.
Optimized Solutions
Here are optimized solutions in various languages:
Java
import java.util.HashMap;
import java.util.Map;
public class SubArray {
public static void findSubArrays(int[] arr) {
Map<Integer, Integer> freqMap = new HashMap<>();
int start = 0, end = 0, maxFreq = 0, minFreq = Integer.MAX_VALUE;
boolean equalCount = false;
while (end < arr.length) {
int currElement = arr[end];
freqMap.put(currElement, freqMap.getOrDefault(currElement, 0) + 1);
if (freqMap.get(currElement) == 0) {
maxFreq = Math.max(maxFreq, end - start + 1);
minFreq = Math.min(minFreq, end - start + 1);
equalCount = maxFreq == minFreq;
}
while (!equalCount && freqMap.get(arr[start]) > 0) {
freqMap.put(arr[start], freqMap.get(arr[start]) - 1);
start++;
}
if (equalCount) {
System.out.println("Sub-array from index " + start + " to " + end + ":");
for (int i = start; i <= end; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
end++;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
findSubArrays(arr);
}
}