#2615

Sum of Distances

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a hashmap to group indices of identical elements and calculates the sum of distances using prefix sums, which significantly reduces the time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hashmap to store indices of each unique number in 'nums'.
  2. 2Step 2: For each unique number, calculate the prefix sums of the indices.
  3. 3Step 3: For each index, use the prefix sums to compute the total distance to all other indices with the same number.
  4. 4Step 4: Store the results in the 'arr' array.
solution.py19 lines
1def sum_of_distances(nums):
2    from collections import defaultdict
3    n = len(nums)
4    arr = [0] * n
5    index_map = defaultdict(list)
6    for i, num in enumerate(nums):
7        index_map[num].append(i)
8    for indices in index_map.values():
9        prefix_sum = [0] * (len(indices) + 1)
10        for i in range(1, len(indices) + 1):
11            prefix_sum[i] = prefix_sum[i - 1] + indices[i - 1]
12        total = 0
13        for i in range(len(indices)):
14            left_count = i
15            right_count = len(indices) - i - 1
16            total += indices[i] * right_count - (prefix_sum[len(indices)] - prefix_sum[i + 1])
17            total += (prefix_sum[i] - prefix_sum[0]) - indices[i] * left_count
18            arr[indices[i]] = total
19    return arr

Complexity note: This complexity is due to the single pass through the array to build the hashmap and another pass through the indices to calculate distances, making it linear.

  • 1Using a hashmap allows us to group indices efficiently.
  • 2Prefix sums help in calculating distances in linear time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.