Member-only story

Leetcode 2121: Intervals Between Identical Elements

Pierre-Marie Poitevin
3 min readJan 6, 2022

--

In this problem, we should return an array which, for each index, contains the sum of intervals for this index, for the indices that contain the same value as arr[i]. This is the problem statement:

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.

We are given a couple of examples to make sure we understood the problem and for testing:

Examples

Solution design

Since we are working with indices with the same value in the array, it is actually more practical to reverse the array to a Map, that maps value to the set of indices with this value.

For example, in the first example, we would obtain the following map:

1 -> [0,4] 
2 -> [1,3]
3 -> [2,5,6]

In addition, I would like the sets in the map to be ordered, for instance [2,5,6]. The reason for that will appear later.

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet