Find the Distinct Difference Array - Problem
You're given a 0-indexed array nums of length n. Your task is to create a distinct difference array that reveals interesting patterns about unique elements!
The distinct difference array diff has the same length n, where each diff[i] represents:
- Number of distinct elements in the prefix
nums[0...i](left side including current) - MINUS the number of distinct elements in the suffix
nums[i+1...n-1](right side excluding current)
Goal: Return the distinct difference array that shows how the balance of unique elements changes at each position.
Example: For nums = [1,2,3,4,5], at index 2 (value 3):
• Prefix [1,2,3] has 3 distinct elements
• Suffix [4,5] has 2 distinct elements
• So diff[2] = 3 - 2 = 1
Input & Output
example_1.py — Basic Example
$
Input:
nums = [1,2,3,4,5]
›
Output:
[-3,-1,1,3,5]
💡 Note:
For each position i: diff[0] = 1-4=-3 (prefix {1}, suffix {2,3,4,5}), diff[1] = 2-3=-1 (prefix {1,2}, suffix {3,4,5}), diff[2] = 3-2=1 (prefix {1,2,3}, suffix {4,5}), diff[3] = 4-1=3 (prefix {1,2,3,4}, suffix {5}), diff[4] = 5-0=5 (prefix {1,2,3,4,5}, empty suffix)
example_2.py — Duplicate Elements
$
Input:
nums = [3,2,3,4,2]
›
Output:
[-2,-1,0,2,3]
💡 Note:
With duplicates, distinct counts are different: diff[0] = 1-3=-2 (prefix {3}, suffix {2,4}), diff[1] = 2-3=-1 (prefix {3,2}, suffix {3,4,2} has {3,4,2}), diff[2] = 2-2=0 (prefix {3,2}, suffix {4,2}), diff[3] = 3-1=2 (prefix {3,2,4}, suffix {2}), diff[4] = 3-0=3 (all distinct elements in prefix)
example_3.py — Single Element
$
Input:
nums = [1]
›
Output:
[1]
💡 Note:
Edge case with single element: prefix has {1} (1 distinct), suffix is empty (0 distinct), so diff[0] = 1 - 0 = 1
Constraints
- 1 ≤ nums.length ≤ 50
- 1 ≤ nums[i] ≤ 50
- Note: Small constraints allow for O(n²) brute force solutions
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with array [1,2,3,4,5] and prepare to slide divider
2
Position 0
Divider after 1: left has {1}, right has {2,3,4,5} → 1-4=-3
3
Position 1
Divider after 2: left has {1,2}, right has {3,4,5} → 2-3=-1
4
Continue
Pattern emerges: prefix grows, suffix shrinks, difference increases
Key Takeaway
🎯 Key Insight: Pre-compute suffix counts once, then build prefix incrementally - this transforms O(n²) nested loops into O(n) linear time!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code