Problem Description
Given an array of positive integers, a subarray is called complete if it contains every distinct integer that appears in the entire array. The task is to count the number of complete subarrays.
Key Insights
- First, determine the total number of distinct elements in the entire array.
- For any starting index, we can identify the smallest ending index such that the subarray contains all distinct elements.
- Once a subarray [i, j] is complete, every subarray [i, k] where k ≥ j is also complete.
- Use a sliding window approach combined with a frequency counter to efficiently expand the window.
- A two-level loop is sufficient since the array length is at most 1000.
Space and Time Complexity
Time Complexity: O(n^2) in the worst-case scenario, where n is the number of elements in the array. Space Complexity: O(n) due to the auxiliary data structures used for counting frequencies.
Solution
We first compute the number of distinct elements in the entire array. Then, for each possible starting index, we use a sliding window to expand the subarray until it becomes complete (i.e., it contains all distinct elements). Once the minimal ending index is found for which the subarray is complete, every subarray ending from that index to the end of the array is also complete. We then add the count for that starting index. The key idea is to only compute the minimal window needed and then infer the number of valid subarrays from it.