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 <= 1050 <= nums[i] <= 109Note: This question is the same as 2121: Intervals Between Identical Elements.
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:
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:
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_sumInstead 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:
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| Case | How to Handle |
|---|---|
| Empty or null input array | Return an empty array immediately to prevent null pointer exceptions or out-of-bounds errors. |
| Array with a single element | Return an array containing a single zero since there are no other identical elements to measure distance to. |
| Array where all elements are identical | 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 | Return an array of all zeros because no element has any other identical occurrences. |
| Maximum constraint array size with large indices | Use 64-bit integer types for distance sums to prevent integer overflow during calculations. |
| Array containing negative numbers and zeros | 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 | Group indices by value using hash maps with dynamic lists to efficiently process only matching elements. |