Intervals Between Identical Elements - Problem

You are given a 0-indexed array of n integers arr.

The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.

Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i].

Note: |x| is the absolute value of x.

Input & Output

Example 1 — Basic Array
$ Input: arr = [2,1,3,1,2,3,3]
Output: [4,2,7,2,4,4,5]
💡 Note: For arr[0]=2: same values at indices 0,4 → distances |0-0|+|0-4| = 0+4 = 4. For arr[1]=1: same values at indices 1,3 → distances |1-1|+|1-3| = 0+2 = 2. For arr[2]=3: same values at indices 2,5,6 → distances |2-2|+|2-5|+|2-6| = 0+3+4 = 7.
Example 2 — All Same Values
$ Input: arr = [10,10,10]
Output: [3,2,3]
💡 Note: For arr[0]=10: distances to indices 0,1,2 → |0-0|+|0-1|+|0-2| = 0+1+2 = 3. For arr[1]=10: distances to indices 0,1,2 → |1-0|+|1-1|+|1-2| = 1+0+1 = 2. For arr[2]=10: distances to indices 0,1,2 → |2-0|+|2-1|+|2-2| = 2+1+0 = 3.
Example 3 — All Different Values
$ Input: arr = [1,2,3,4]
Output: [0,0,0,0]
💡 Note: Each element is unique, so each only matches with itself at distance 0. All intervals are 0.

Constraints

  • n == arr.length
  • 1 ≤ n ≤ 105
  • 1 ≤ arr[i] ≤ 105

Visualization

Tap to expand
Intervals Between Identical ElementsSum distances from each element to all elements with same value21312330123456Input: [2,1,3,1,2,3,3]Value 2 at indices 0,4: distances = |0-0|+|0-4| = 4, |4-0|+|4-4| = 4Value 1 at indices 1,3: distances = |1-1|+|1-3| = 2, |3-1|+|3-3| = 2Value 3 at indices 2,5,6: distances = 7, 4, 5 respectivelyOutput: [4,2,7,2,4,4,5]Each element's result is sum of distances to all elements with same value
Understanding the Visualization
1
Input Array
Array with potentially duplicate values at different indices
2
Find Matches
For each element, find all positions with same value
3
Calculate Distances
Sum up absolute differences between current index and all matching indices
Key Takeaway
🎯 Key Insight: Use prefix sums to calculate all distances mathematically instead of nested loops for O(n) solution
Asked in
Facebook 12 Amazon 8 Google 6
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen