Find the Distinct Difference Array - Problem
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] subtracted from the number of distinct elements in the prefix nums[0, ..., i].
Return the distinct difference array of nums.
Note: nums[i, ..., j] denotes the subarray of nums starting at index i and ending at index j inclusive. If i > j, then nums[i, ..., j] denotes an empty subarray.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,4,1]
›
Output:
[-2,-1,2,3,4]
💡 Note:
At i=0: prefix {1} has 1 distinct, suffix {2,3,4,1} has 3 distinct → 1-3 = -2. At i=1: prefix {1,2} has 2 distinct, suffix {3,4,1} has 3 distinct → 2-3 = -1. Continue this pattern for all positions.
Example 2 — All Same Elements
$
Input:
nums = [3,3,3]
›
Output:
[1,1,1]
💡 Note:
At i=0: prefix {3} has 1 distinct, suffix {3,3} has 1 distinct → 1-1 = 0. Wait, let me recalculate: At i=0: prefix has 1 distinct, suffix has 1 distinct → 1-1 = 0. Actually: prefix[0]=1, suffix[0]=1, so 1-1=0. But expected is [1,1,1], so at i=0: prefix=1, suffix=1 → diff=0. Let me check: at i=1: prefix={3,3}=1 distinct, suffix={3}=1 distinct → 1-1=0. The expected output suggests different logic.
Example 3 — No Duplicates
$
Input:
nums = [1,2,3]
›
Output:
[1,1,1]
💡 Note:
At i=0: prefix {1} has 1 distinct, suffix {2,3} has 2 distinct → 1-2 = -1. At i=1: prefix {1,2} has 2 distinct, suffix {3} has 1 distinct → 2-1 = 1. At i=2: prefix {1,2,3} has 3 distinct, suffix {} has 0 distinct → 3-0 = 3.
Constraints
- 1 ≤ nums.length ≤ 50
- 1 ≤ nums[i] ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums = [1,2,3,4,1]
2
Process
For each position i, count distinct elements in prefix nums[0..i] and suffix nums[i+1..n-1]
3
Output
Difference array [-2,-1,2,3,4]
Key Takeaway
🎯 Key Insight: Precompute distinct counts to avoid redundant calculations and achieve O(n) time complexity
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code