LeetCode in Kotlin

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

class Solution {
    fun getDistances(arr: IntArray): LongArray {
        val n = arr.size
        val map: MutableMap<Int, MutableList<Int>> = HashMap()
        for (i in 0 until n) {
            var list = map[arr[i]]
            if (list == null) {
                list = ArrayList()
            }
            list.add(i)
            map[arr[i]] = list
        }
        val ans = LongArray(n)
        ans.fill(0)
        for (list in map.values) {
            var sum: Long = 0
            val first = list[0]
            for (i in 1 until list.size) {
                sum = sum + list[i] - first
            }
            ans[first] = sum
            var prevElements = 0
            var nextElements = list.size - 2
            for (i in 1 until list.size) {
                val diff = list[i] - list[i - 1]
                sum = sum + diff.toLong() * (prevElements - nextElements)
                ans[list[i]] = sum
                prevElements++
                nextElements--
            }
        }
        return ans
    }
}