Problem Statement:
Given an array arr
consisting of only the integers 0
, 1
, and 2
, the task is to find the number of contiguous subarrays that contain at least one occurrence of each integer (0, 1, and 2).
Approach:
To solve this problem, we can use the sliding window (two-pointer) technique in combination with a hashmap (or unordered_map) to efficiently count the number of valid subarrays that include at least one 0
, 1
, and 2
. The key idea is to maintain a window that expands to include more elements and contracts when it has included at least one of each of the required numbers.
Time Complexity:
-
Time Complexity: The algorithm runs in
O(N)
time, whereN
is the length of the array. This is because each element is processed at most twice—once by thej
pointer and once by thei
pointer. -
Space Complexity: The space complexity is
O(1)
in terms of the number of distinct elements (sincecountMap
only stores counts for0
,1
, and2
).