You are given a 0-indexed array of n integers arr.
The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.
Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i].
Note: |x| is the absolute value of x.
Example 1:
Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
Example 2:
Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
Constraints:
n == arr.length1 <= n <= 1051 <= arr[i] <= 105Note: This question is the same as 2615: Sum of Distances.
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:
Imagine you have a long list of items and you want to calculate how far apart all identical items are from one another. The brute force approach achieves this by examining every single item in the list one by one and manually measuring the distance to every other matching item.
Here's how the algorithm would work step-by-step:
def get_distances_brute_force(input_array):
# Initialize result list to store total distance for each element
result_distances = [0] * len(input_array)
# Iterate through every single item to measure distances to its matches
for current_index in range(len(input_array)):
total_distance = 0
for compare_index in range(len(input_array)):
if input_array[current_index] == input_array[compare_index]:
total_distance += abs(current_index - compare_index)
result_distances[current_index] = total_distance
# Collect all final calculated totals to return the complete answer
return result_distancesInstead of checking every item one by one against all its matches, the optimal approach groups identical items together by their positions. It then uses a clever mathematical shortcut to calculate the total distance between matching items efficiently in a single pass.
Here's how the algorithm would work step-by-step:
class Solution:
def get_distances(self, input_sequence: list[int]) -> list[int]:
from collections import defaultdict
position_map = defaultdict(list)
for sequence_index, item_value in enumerate(input_sequence):
position_map[item_value].append(sequence_index)
# Grouping identical items by their positions allows us to process each distinct value independently.
result_distances = [0] * len(input_sequence)
for item_value, position_list in position_map.items():
total_occurrences = len(position_list)
prefix_sum_value = 0
# We track running sums to efficiently compute distances without nested loops for each match.
for current_index in range(total_occurrences):
position_value = position_list[current_index]
left_contribution = (position_value * current_index) - prefix_sum_value
right_contribution = (sum(position_list[current_index + 1:]) - (position_value * (total_occurrences - 1 - current_index)))
result_distances[position_value] = left_contribution + right_contribution
prefix_sum_value += position_value
# Combining all computed contributions gives the final interval distances for every item.
return result_distances| Case | How to Handle |
|---|---|
| Empty or single-element arrays | Return an empty array or an array with a single zero since no identical element pairs exist. |
| Array with all identical elements | Precompute total sums and use prefix sums to calculate absolute differences in O(1) time per element. |
| Array with all unique elements | Return an array of all zeros since no element appears more than once. |
| Large input size up to one hundred thousand elements | Use a hash map to group indices by value and compute prefix sums to achieve optimal O(N) time complexity. |
| Integer overflow from large index sums | Use 64-bit integers for index accumulation since the sum of differences can exceed standard 32-bit integer limits. |
| Negative numbers and zeros mixed in the input | Treat values purely as hash keys without restriction since negative integers and zero work seamlessly in hash maps. |
| Highly skewed distribution with one frequent element and many unique ones | Ensure the index-grouping data structure efficiently scales without performance degradation from hash collisions. |