Leetcode 2670. Find the Distinct Difference Array
You are given a 0-indexed array nums
of length n
. The distinct difference array of nums
is an array diff
of length n
such that diff[i]
is equal to the number of distinct elements in the suffix nums[i+1, n-1]
minus the number of distinct elements in the prefix nums[0, i]
.
Return the distinct difference array of nums
.
To solve this problem, we’ll break it down into several steps:
import java.util.*;
public class DistinctDifferenceArray {
public static int[] distinctDifferenceArray(int[] nums) {
int n = nums.length;
int[] prefixDistinctCount = new int[n];
int[] suffixDistinctCount = new int[n];
int[] diff = new int[n];
// Set to track distinct elements in prefix
Set<Integer> prefixSet = new HashSet<>();
for (int i = 0; i < n; i++) {
prefixSet.add(nums[i]);
prefixDistinctCount[i] = prefixSet.size();
}
// Set to track distinct elements in suffix
Set<Integer> suffixSet = new HashSet<>();
for (int i = n - 1; i >= 0; i--) {
suffixSet.add(nums[i]);
suffixDistinctCount[i] = suffixSet.size();
}
// Compute the diff array
for (int i = 0; i < n - 1; i++) {
diff[i] = suffixDistinctCount[i + 1] - prefixDistinctCount[i];
}
// The last element remains as -prefixDistinctCount[n-1] as suffix beyond this is EMPTY
diff[n - 1] = -prefixDistinctCount[n - 1];
return diff;
}
public static void main(String[] args) {
int[] nums = {5, 2, 5, 2, 1};
System.out.println(Arrays.toString(distinctDifferenceArray(nums)));
// Example output for given input []
}
}
This approach ensures that we efficiently calculate the distinct differences with minimal passes through the array. The use of sets ensures that we are accurately tracking distinct elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?