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,1,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. At i=2: prefix {1,2,3} has 3 distinct, suffix {4,1} has 2 distinct → 3-2 = 1. At i=3: prefix {1,2,3,4} has 4 distinct, suffix {1} has 1 distinct → 4-1 = 3. At i=4: prefix {1,2,3,4,1} has 4 distinct, suffix {} has 0 distinct → 4-0 = 4.
Example 2 — All Same Elements
$
Input:
nums = [3,3,3]
›
Output:
[0,0,1]
💡 Note:
At i=0: prefix {3} has 1 distinct, suffix {3,3} has 1 distinct → 1-1 = 0. At i=1: prefix {3,3} has 1 distinct, suffix {3} has 1 distinct → 1-1 = 0. At i=2: prefix {3,3,3} has 1 distinct, suffix {} has 0 distinct → 1-0 = 1.
Example 3 — No Duplicates
$
Input:
nums = [1,2,3]
›
Output:
[-1,1,3]
💡 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code