2615. Sum of Distances (same as 2121. Intervals Between Identical Elements)

T: O(n)
S: O(n)
```java
class Solution {
    public long[] distance(int[] nums) {
        Map<Integer, Long> sum = new HashMap<>();
        Map<Integer, Integer> count = new HashMap<>();
        int n = nums.length;
        long[] result = new long[n];
        for (int i = 0; i < n; i++) {
            result[i] += i*(long)count.getOrDefault(nums[i], 0) - sum.getOrDefault(nums[i], 0L);
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            sum.put(nums[i], sum.getOrDefault(nums[i], 0L) + i);
        }

        sum = new HashMap<>();
        count = new HashMap<>();
        for (int i = n-1; i >= 0; i--) {
            result[i] += (n-i-1)*(long)count.getOrDefault(nums[i], 0) - sum.getOrDefault(nums[i], 0L);
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            sum.put(nums[i], sum.getOrDefault(nums[i], 0L) + (n-i-1));
        }
        return result;
    }
}

/*
T: O(n)
S: O(n)

assume they are all same
[1,1,1,1,1]
 a b c d e

arr[c] = |c - a| + |c - b| 
+ |c - d| + |c - e|

so in the left of c

2*c - (a+b)
-> same left count * index - (same left sum)

right

2 *c - (d+e)

->
same right count * (len - index + 1) - (same right sum)

sum:   is sum of index
count : count of same index
*/
```

Last updated