22. Sub-arrays with Equal Number of Occurrences
The problem can be found at the following link: Question Link
Problem Description
Given an array arr[] and two integers x and y, find the number of sub-arrays where the number of occurrences of x is equal to the number of occurrences of y.
Example:
Input:
arr = [1, 2, 1], x = 1, y = 2Output:
2Explanation:
The sub-arrays where the occurrences of
xandyare the same are:[1, 2], bothxandyoccur once.[2, 1], bothxandyoccur once.
Input:
arr = [1, 2, 1], x = 4, y = 6Output:
6Explanation:
All sub-arrays have equal occurrences (0) of both
xandy.
My Approach
Prefix Difference Array:
Create a difference count (
diffCount) to store the difference between occurrences ofxandyat every index.We maintain a running
diffthat increases by 1 whenxoccurs and decreases by 1 whenyoccurs. This helps track sub-arrays wherexandyappear an equal number of times.The goal is to find how many times the same
diffhas appeared indiffCount, which means there exists a sub-array between these two occurrences where the number ofxandyoccurrences are equal.
Efficient HashMap Usage:
Use a hash map to store the occurrences of the differences at each step.
For each index, the value of the current difference in
diffCountgives the number of sub-arrays that maintain the equal occurrence ofxandy.
Result Accumulation:
Increment the result by the number of times the current
diffhas been seen.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the size of the array. We iterate through the array once and use a hash map to store prefix sums.Expected Auxiliary Space Complexity: O(n), as we store the differences in a hash map.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated