Taro Logo

Sum of Distances

#160 Most AskedMedium
0 views
Topics:
Arrays

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, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. 
When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. 
When i = 4, arr[4] = 0 because there is no other index with value 2. 

Example 2:

Input: nums = [0,5,3]
Output: [0,0,0]
Explanation: Since each element in nums is distinct, arr[i] = 0 for all i.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109

Note: This question is the same as 2121: Intervals Between Identical Elements.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values and the maximum length of the input array `nums`?
  2. Can the array contain negative numbers, zeros, or is it strictly limited to positive integers?
  3. How should we handle elements that appear only once in the array? Should their corresponding output value be 0?
  4. Should the returned array be of the same length and maintain the exact same index correspondence as the input `nums`?
  5. Can the input array be empty or null, and what should be returned in such cases?

Brute Force Solution

Approach

To find the sum of distances for all items, the brute force approach examines every single item one by one. For each item, it measures the distance to every other item and adds them all together before moving on to the next one.

Here's how the algorithm would work step-by-step:

  1. Pick the first item as your starting point.
  2. Measure the distance from this item to the second item, then to the third item, and so on for every other item.
  3. Add up all those individual distances to get a total sum for your starting item.
  4. Move to the next item and repeat the entire measuring process for it.
  5. Continue this process until every single item has been used as the starting point and had its distances to all others measured.
  6. Add up the totals gathered from each item, keeping in mind that some measurements might need adjustment depending on the exact rules of the problem.
  7. Select the final combined result as your answer.

Code Implementation

def calculate_sum_of_distances(item_positions):
    total_distance_sum = 0
    
    # Iterate through every item to use each one as the starting point for distance measurement
    for starting_item_index in range(len(item_positions)):
        
        # Measure and accumulate the distance from the current starting item to every other item
        for target_item_index in range(len(item_positions)):
            distance_between_items = abs(item_positions[starting_item_index] - item_positions[target_item_index])
            total_distance_sum += distance_between_items
            
    # Return the final combined result representing the sum of all calculated distances
    return total_distance_sum

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items picked as a starting point in the outer loop, the algorithm measures the distance to every other item using an inner loop. This means we perform n distance measurements for the first item, n for the second, and so on for all n items. This totals approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute force approach described only uses a few primitive scalar variables, such as loop counters and running sums, to measure distances between items. No additional auxiliary data structures like temporary lists or hash maps are created during the process. Consequently, the extra memory required remains constant regardless of the input size N, resulting in an auxiliary space complexity of O(1).

Optimal Solution

Approach

Instead of recalculating the distance between every single pair of items from scratch, the optimal approach relies on a clever mathematical shortcut. It calculates the total distance by looking at how the distance changes smoothly as you move from one item to the next.

Here's how the algorithm would work step-by-step:

  1. Imagine standing at the very first item and calculating the total distance to all the other items ahead of you.
  2. Notice how moving your position one step to the right affects your distance to everything: you get one step closer to all the items behind you, but one step farther away from all the items ahead of you.
  3. Use this relationship to instantly figure out the total distance for the second item, just by looking at the total distance you calculated for the first item and adjusting for how many items are behind and ahead.
  4. Continue this sliding process smoothly from left to right across all the items, updating your running total in a single continuous pass.
  5. By avoiding the need to measure every individual pair from the beginning every time, you arrive at the final answer remarkably fast.

Code Implementation

def sum_of_distances(item_positions):
    total_items = len(item_positions)
    if total_items <= 1:
        return [0] * total_items

    distance_results = [0] * total_items
    initial_distance_sum = 0

    # We calculate the baseline distance from the first item to all other items.
    for item_index in range(1, total_items):
        initial_distance_sum += item_positions[item_index] - item_positions[0]

    distance_results[0] = initial_distance_sum

    # We update distances incrementally by shifting our reference point to the right.
    for current_index in range(1, total_items):
        items_behind_count = current_index
        items_ahead_count = total_items - current_index
        position_difference = item_positions[current_index] - item_positions[current_index - 1]

        initial_distance_sum += position_difference * (items_behind_count - items_ahead_count)
        distance_results[current_index] = initial_distance_sum

    # We return the accumulated total distances for every starting position.
    return distance_results

Big(O) Analysis

Time Complexity
O(n) – To find the sum of distances for all items, the algorithm uses a single initial pass to compute the total distance from the first item to all others, and a second continuous pass to shift the perspective across the array. Each of these two linear passes iterates through all n items sequentially without any nested loops or redundant pair checking. The total operations scale linearly as roughly 2n steps since we process every element a constant number of times. Dropping the constant factor simplifies the final time complexity to O(n).
Space Complexity
O(1) – The algorithm relies entirely on a constant number of primitive variables to maintain running totals and index pointers during the sliding process. No auxiliary arrays, hash maps, or recursion stacks are created that scale with the input size N. As a result, the extra memory usage remains completely fixed regardless of how many items are being processed.

Edge Cases

Empty or null input array
How to Handle:
Return an empty array immediately to prevent null pointer exceptions or out-of-bounds errors.
Array with a single element
How to Handle:
Return an array containing a single zero since there are no other identical elements to measure distance to.
Array where all elements are identical
How to Handle:
Maintain running prefix sums and counts of previous occurrences to compute the total distance in O(N) time without nested loops.
Array with all unique elements
How to Handle:
Return an array of all zeros because no element has any other identical occurrences.
Maximum constraint array size with large indices
How to Handle:
Use 64-bit integer types for distance sums to prevent integer overflow during calculations.
Array containing negative numbers and zeros
How to Handle:
Treat values purely as hash map keys since values themselves do not impact index distance calculations.
Highly skewed distribution with one frequent value and many unique ones
How to Handle:
Group indices by value using hash maps with dynamic lists to efficiently process only matching elements.
0/257 completed