Advertisement

Sum of Distances - LeetCode 2615 Solution

Sum of Distances - Complete Solution Guide

Sum of Distances is LeetCode problem 2615, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given a 0-indexed integer array nums . There exists an array arr of length nums.length , where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i . If there is no such j , set arr[i] to be 0 . Return the array arr . Example 1: Input: nums = [1,3,1,1,2] Output: [5,0,3,4,0] Explanation: When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2

Detailed Explanation

The problem requires calculating the sum of absolute distances between each index `i` in an array `nums` and all other indices `j` that hold the same value as `nums[i]`. The result is an array `arr` where `arr[i]` is this calculated sum. If no other index has the same value as `nums[i]`, then `arr[i]` is 0. Essentially, for each number in the input array, we need to find all other positions where the same number appears and compute the sum of the absolute differences between their indices.

Solution Approach

The provided solution utilizes a two-pass approach combined with hash maps to achieve an O(n) time complexity. The algorithm first iterates through the array from left to right, and then from right to left. In each pass, it maintains a count and a prefix sum for each distinct number encountered. The prefix sum stores the sum of indices where the number has appeared so far. The count stores how many times the number has appeared so far. These values allow for calculating the sum of distances to the 'left' and to the 'right' of an index efficiently, and then these two partial sums are added together to compute the final result.

Step-by-Step Algorithm

  1. Step 1: Initialize an array `ans` of the same size as `nums` to store the results, filled with zeros.
  2. Step 2: Create two hash maps (or equivalent): `counts` to store the number of occurrences of each number encountered so far, and `prefix_sums` to store the sum of the indices where each number has appeared so far.
  3. Step 3: Iterate through the `nums` array from left to right (first pass). For each element `nums[i]`, calculate the sum of distances to the elements on the left with same value using the formula: `counts[nums[i]] * i - prefix_sums[nums[i]]`. Add this value to `ans[i]`.
  4. Step 4: After computing the left distances, update the `counts` and `prefix_sums` hash maps for the current element `nums[i]` by incrementing the count and adding the index `i` to the prefix sum.
  5. Step 5: Clear the `counts` and `prefix_sums` hash maps to prepare for the second pass.
  6. Step 6: Iterate through the `nums` array from right to left (second pass). For each element `nums[i]`, calculate the sum of distances to the elements on the right with the same value using the formula: `prefix_sums[nums[i]] - counts[nums[i]] * i`. Add this value to `ans[i]`.
  7. Step 7: After computing the right distances, update the `counts` and `prefix_sums` hash maps for the current element `nums[i]` by incrementing the count and adding the index `i` to the prefix sum.
  8. Step 8: Return the `ans` array.

Key Insights

  • Insight 1: Using a hash map (or equivalent) to store the indices for each distinct number in the array allows for efficient lookup.
  • Insight 2: Calculating the sum directly for each element would result in O(n^2) time complexity. A better approach is to use prefix sums to optimize the distance calculation.
  • Insight 3: Two passes are required: one from left to right and another from right to left, accumulating the distances incrementally to avoid redundant calculations.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table, Prefix Sum.

Companies

Asked at: BNY Mellon.