LeetCode Problem

How to Solve Sum of Distances

To solve this problem, we need to calculate an array where each element represents the sum of the absolute differences between indices for the same value in the input array. The key to an efficient solution lies in scanning the array while using a hash table to store the indices of previously seen elements. Using a prefix sum approach can also optimize this solution by maintaining running totals for distances.

GhostInterview Help

Need help with Sum of Distances without spending extra time grinding it?

GhostInterview can read Sum of Distances from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #2615Array scanning plus hash lookupReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Array scanning plus hash lookup
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve this problem, we need to calculate an array where each element represents the sum of the absolute differences between indices for the same value in the input array. The key to an efficient solution lies in scanning the array while using a hash table to store the indices of previously seen elements. Using a prefix sum approach can also optimize this solution by maintaining running totals for distances.

Problem Statement

You are given a 0-indexed integer array nums. Your task is to create a new array arr of the same length as nums, where each element arr[i] represents the sum of the absolute differences between the index i and all other indices j where nums[j] == nums[i] and j != i. If no such index exists, set arr[i] to 0.

Return the array arr. Consider using efficient techniques such as scanning the array and leveraging hash tables or prefix sums to optimize the solution for large inputs, where the size of nums can be as large as 10^5.

Examples

Example 1

Input: nums = [1,3,1,1,2]

Output: [5,0,3,4,0]

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]

Since each element in nums is distinct, arr[i] = 0 for all i.

Constraints

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

Solution Approach

Array Scanning with Hash Table

Iterate through the array, storing the indices of each element in a hash table. For each index, calculate the sum of absolute differences to all other indices with the same value using the stored indices. This approach helps avoid recalculating distances multiple times.

Prefix Sum Optimization

An optimized solution involves using a prefix sum array to calculate running totals of indices for each distinct value. This reduces the need to loop through the same elements multiple times and provides a faster solution for larger arrays.

Efficient Index Lookup

Use a hash table to track indices of repeated elements. This enables quick lookup for elements already encountered, helping to efficiently calculate the sum of absolute differences between indices.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

The time complexity depends on the final approach. The basic array scanning with hash table solution can be linear, O(n), where n is the length of the input array. If prefix sums are used, the time complexity remains O(n), but it may involve more intermediate calculations. The space complexity depends on the use of the hash table or prefix sum array, which also scales linearly with the input size, O(n).

What Interviewers Usually Probe

  • The candidate demonstrates an understanding of using hash tables for efficient lookups.
  • The candidate considers optimizing the solution with prefix sums, showing awareness of performance constraints.
  • The candidate clearly explains the relationship between array scanning and hash lookup in this problem.

Common Pitfalls or Variants

Common pitfalls

  • Overcomplicating the problem with unnecessary nested loops or recalculating distances multiple times.
  • Not leveraging the power of hash tables for fast index lookups, which can lead to inefficient solutions.
  • Failing to recognize the value of using a prefix sum approach, resulting in suboptimal performance for large arrays.

Follow-up variants

  • Modify the problem to consider different types of distance metrics, such as squared differences.
  • Instead of summing distances, return the maximum distance for each element's repeated occurrences.
  • Extend the problem to handle multidimensional arrays where the comparison of elements occurs across multiple axes.

How GhostInterview Helps

  • GhostInterview suggests optimized approaches like prefix sum and hash lookup, improving efficiency.
  • The platform helps by providing clear explanations for key concepts such as array scanning and hash tables.
  • GhostInterview breaks down the problem into digestible steps, aiding in developing a well-structured solution.

Topic Pages

FAQ

What is the main pattern behind solving the Sum of Distances problem?

The problem revolves around scanning the array and using hash tables for efficient index lookup and distance calculation. Optimizations like prefix sums can further enhance performance.

How can I optimize the Sum of Distances problem?

Using a hash table to store indices for repeated elements and applying a prefix sum technique for running totals can significantly optimize the solution.

What is the time complexity of the Sum of Distances problem?

The time complexity is generally O(n), where n is the length of the input array, especially with optimized techniques like prefix sums and hash lookups.

What should I avoid when solving the Sum of Distances problem?

Avoid using nested loops or recalculating distances multiple times, which can lead to inefficient solutions.

Can I use prefix sums for the Sum of Distances problem?

Yes, prefix sums can be used to optimize the solution by maintaining running totals of indices for faster distance calculations.

GhostInterview Solver

Need direct help with Sum of Distances instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Sum of Distances from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.