LeetCode-in-Java

2121. Intervals Between Identical Elements

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.

Example 1:

Input: arr = [2,1,3,1,2,3,3]

Output: [4,2,7,2,4,4,5]

Explanation:

Example 2:

Input: arr = [10,5,10,10]

Output: [5,0,3,4]

Explanation:

Constraints:

Solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public long[] getDistances(int[] arr) {
        int n = arr.length;
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            List<Integer> list = map.get(arr[i]);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(i);
            map.put(arr[i], list);
        }
        long[] ans = new long[n];
        Arrays.fill(ans, 0);
        for (List<Integer> list : map.values()) {
            long sum = 0;
            int first = list.get(0);
            for (int i = 1; i < list.size(); i++) {
                sum = sum + list.get(i) - first;
            }
            ans[first] = sum;
            int prevElements = 0;
            int nextElements = list.size() - 2;
            for (int i = 1; i < list.size(); i++) {
                int diff = list.get(i) - list.get(i - 1);
                sum = sum + (long) diff * (prevElements - nextElements);
                ans[list.get(i)] = sum;
                prevElements++;
                nextElements--;
            }
        }
        return ans;
    }
}