Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
Example 2:
Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
Constraints:
n == arr.length1 <= n <= 1051 <= arr[i] <= 105Note: This question is the same as 2615: Sum of Distances.
Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[2,1,3,1,2,3,3]
[10,5,10,10]
continuous-subarray-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2121: Intervals Between Identical Elements
class Solution {
public long[] getDistances(int[] arr) {
Map<Integer, List<Integer>> d = new HashMap<>();
int n = arr.length;
for (int i = 0; i < n; ++i) {
d.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
long[] ans = new long[n];
for (List<Integer> v : d.values()) {
int m = v.size();
long val = 0;
for (int e : v) {
val += e;
}
val -= (m * v.get(0));
for (int i = 0; i < v.size(); ++i) {
int delta = i >= 1 ? v.get(i) - v.get(i - 1) : 0;
val += i * delta - (m - i) * delta;
ans[v.get(i)] = val;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2121: Intervals Between Identical Elements
func getDistances(arr []int) []int64 {
d := make(map[int][]int)
n := len(arr)
for i, v := range arr {
d[v] = append(d[v], i)
}
ans := make([]int64, n)
for _, v := range d {
m := len(v)
val := 0
for _, e := range v {
val += e
}
val -= m * v[0]
for i, p := range v {
delta := 0
if i >= 1 {
delta = v[i] - v[i-1]
}
val += i*delta - (m-i)*delta
ans[p] = int64(val)
}
}
return ans
}
# Accepted solution for LeetCode #2121: Intervals Between Identical Elements
class Solution:
def getDistances(self, arr: List[int]) -> List[int]:
d = defaultdict(list)
n = len(arr)
for i, v in enumerate(arr):
d[v].append(i)
ans = [0] * n
for v in d.values():
m = len(v)
val = sum(v) - v[0] * m
for i, p in enumerate(v):
delta = v[i] - v[i - 1] if i >= 1 else 0
val += i * delta - (m - i) * delta
ans[p] = val
return ans
// Accepted solution for LeetCode #2121: Intervals Between Identical Elements
/**
* [2121] Intervals Between Identical Elements
*
* 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.
*
* Example 1:
*
* Input: arr = [2,1,3,1,2,3,3]
* Output: [4,2,7,2,4,4,5]
* Explanation:
* - Index 0: Another 2 is found at index 4. |0 - 4| = 4
* - Index 1: Another 1 is found at index 3. |1 - 3| = 2
* - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7
* - Index 3: Another 1 is found at index 1. |3 - 1| = 2
* - Index 4: Another 2 is found at index 0. |4 - 0| = 4
* - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4
* - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
*
* Example 2:
*
* Input: arr = [10,5,10,10]
* Output: [5,0,3,4]
* Explanation:
* - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5
* - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.
* - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3
* - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
*
*
* Constraints:
*
* n == arr.length
* 1 <= n <= 10^5
* 1 <= arr[i] <= 10^5
*
*
* Note: This question is the same as <a href="https://leetcode.com/problems/sum-of-distances/description/" target="_blank"> 2615: Sum of Distances.</a>
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/intervals-between-identical-elements/
// discuss: https://leetcode.com/problems/intervals-between-identical-elements/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn get_distances(arr: Vec<i32>) -> Vec<i64> {
vec![]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2121_example_1() {
let arr = vec![2, 1, 3, 1, 2, 3, 3];
let result = vec![4, 2, 7, 2, 4, 4, 5];
assert_eq!(Solution::get_distances(arr), result);
}
#[test]
#[ignore]
fn test_2121_example_2() {
let arr = vec![10, 5, 10, 10];
let result = vec![5, 0, 3, 4];
assert_eq!(Solution::get_distances(arr), result);
}
}
// Accepted solution for LeetCode #2121: Intervals Between Identical Elements
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2121: Intervals Between Identical Elements
// class Solution {
// public long[] getDistances(int[] arr) {
// Map<Integer, List<Integer>> d = new HashMap<>();
// int n = arr.length;
// for (int i = 0; i < n; ++i) {
// d.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
// }
// long[] ans = new long[n];
// for (List<Integer> v : d.values()) {
// int m = v.size();
// long val = 0;
// for (int e : v) {
// val += e;
// }
// val -= (m * v.get(0));
// for (int i = 0; i < v.size(); ++i) {
// int delta = i >= 1 ? v.get(i) - v.get(i - 1) : 0;
// val += i * delta - (m - i) * delta;
// ans[v.get(i)] = val;
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.