Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2570aae

Browse files
committed
Add solution #2121
1 parent 8b2704b commit 2570aae

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,758 LeetCode solutions in JavaScript
1+
# 1,759 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1624,6 +1624,7 @@
16241624
2117|[Abbreviating the Product of a Range](./solutions/2117-abbreviating-the-product-of-a-range.js)|Hard|
16251625
2119|[A Number After a Double Reversal](./solutions/2119-a-number-after-a-double-reversal.js)|Easy|
16261626
2120|[Execution of All Suffix Instructions Staying in a Grid](./solutions/2120-execution-of-all-suffix-instructions-staying-in-a-grid.js)|Medium|
1627+
2121|[Intervals Between Identical Elements](./solutions/2121-intervals-between-identical-elements.js)|Medium|
16271628
2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
16281629
2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
16291630
2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)