|
| 1 | +/** |
| 2 | + * 2121. Intervals Between Identical Elements |
| 3 | + * https://leetcode.com/problems/intervals-between-identical-elements/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed array of n integers arr. |
| 7 | + * |
| 8 | + * The interval between two elements in arr is defined as the absolute difference between their |
| 9 | + * indices. More formally, the interval between arr[i] and arr[j] is |i - j|. |
| 10 | + * |
| 11 | + * Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] |
| 12 | + * and each element in arr with the same value as arr[i]. |
| 13 | + * |
| 14 | + * Note: |x| is the absolute value of x. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} arr |
| 19 | + * @return {number[]} |
| 20 | + */ |
| 21 | +var getDistances = function(arr) { |
| 22 | + const valueIndices = new Map(); |
| 23 | + const result = new Array(arr.length).fill(0); |
| 24 | + |
| 25 | + for (let i = 0; i < arr.length; i++) { |
| 26 | + if (!valueIndices.has(arr[i])) { |
| 27 | + valueIndices.set(arr[i], []); |
| 28 | + } |
| 29 | + valueIndices.get(arr[i]).push(i); |
| 30 | + } |
| 31 | + |
| 32 | + for (const indices of valueIndices.values()) { |
| 33 | + let prefixSum = 0; |
| 34 | + for (let i = 1; i < indices.length; i++) { |
| 35 | + prefixSum += indices[i] - indices[0]; |
| 36 | + } |
| 37 | + |
| 38 | + result[indices[0]] = prefixSum; |
| 39 | + |
| 40 | + for (let i = 1; i < indices.length; i++) { |
| 41 | + const diff = indices[i] - indices[i - 1]; |
| 42 | + prefixSum += diff * (i - (indices.length - i)); |
| 43 | + result[indices[i]] = prefixSum; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return result; |
| 48 | +}; |
0 commit comments