Problem Description
Given a 0-indexed array nums of length n, we want to compute an array diff where diff[i] is the difference between the number of distinct elements in the prefix nums[0...i] and the number of distinct elements in the suffix nums[i+1...n-1]. For cases where the suffix is empty (i.e. when i is the last index), consider its distinct count as 0.
Key Insights
- We can precompute the number of distinct elements in the prefix for each index by iterating from left to right while maintaining a set.
- Similarly, we compute the distinct count for the suffix by iterating from right to left and using a set.
- For each index i, the answer is simply prefix_distinct_count[i] minus (suffix_distinct_count[i+1] if i+1 exists, otherwise 0).
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array (each element is processed twice). Space Complexity: O(n) for storing the prefix and suffix counts, plus O(k) for the sets (with k ≤ n).
Solution
We solve the problem by performing two passes over the array. First, we traverse the array from the beginning to calculate, for every index, the total number of distinct elements encountered in the prefix. Then, we perform a reverse traversal to calculate the number of distinct elements in the suffix (from i+1 to end). Finally, we compute the difference between these two values for every index i to form the distinct difference array. The use of sets to track distinct elements ensures that we count each unique element only once.