-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2121-intervals-between-identical-elements.js
More file actions
48 lines (42 loc) · 1.32 KB
/
2121-intervals-between-identical-elements.js
File metadata and controls
48 lines (42 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 2121. Intervals Between Identical Elements
* https://leetcode.com/problems/intervals-between-identical-elements/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[]} arr
* @return {number[]}
*/
var getDistances = function(arr) {
const valueIndices = new Map();
const result = new Array(arr.length).fill(0);
for (let i = 0; i < arr.length; i++) {
if (!valueIndices.has(arr[i])) {
valueIndices.set(arr[i], []);
}
valueIndices.get(arr[i]).push(i);
}
for (const indices of valueIndices.values()) {
let prefixSum = 0;
for (let i = 1; i < indices.length; i++) {
prefixSum += indices[i] - indices[0];
}
result[indices[0]] = prefixSum;
for (let i = 1; i < indices.length; i++) {
const diff = indices[i] - indices[i - 1];
prefixSum += diff * (i - (indices.length - i));
result[indices[i]] = prefixSum;
}
}
return result;
};