Taro Logo

Intervals Between Identical Elements

Medium
Asked by:
TuSimple
Wayve
5 views
Topics:
Arrays

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.length
  • 1 <= n <= 105
  • 1 <= arr[i] <= 105

Note: This question is the same as 2615: Sum of Distances.

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 inside the array, and can the array contain negative numbers and zeros?
  2. How should we handle an empty array or an array with a single element—should it return an empty array?
  3. Are the indices 0-based, and should the resulting array contain 64-bit integers (like long in Java/C++) to prevent potential integer overflow when summing distances?
  4. Could you clarify if 'identical elements' refers strictly to elements with the exact same value, and what is the expected return type for the output array?
  5. If an element appears only once in the array, should its corresponding interval sum in the output be 0?

Brute Force Solution

Approach

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:

  1. Pick the very first item on the list to examine.
  2. Look through the rest of the list to find every other item that matches the one you picked.
  3. Whenever you find a match, measure the distance between the starting item and that matching item.
  4. Add up all those measured distances to get the total distance for the item you are currently holding.
  5. Move on to the next item in the list and repeat the entire matching and measuring process all over again.
  6. Do this for every single item from the beginning to the end of the list until every match has been compared.
  7. Collect all the final calculated totals to get your complete set of answers.

Code Implementation

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_distances

Big(O) Analysis

Time Complexity
O(n²) – For each of the n elements in the array, we iterate through the list to find every other identical element and measure its distance. For the first element we inspect up to n-1 potential matches, and for subsequent elements we repeat similar linear scans across the input size n. This nested pair checking results in approximately n * n/2 total operations, which simplifies to the quadratic Big O time complexity of O(n²).
Space Complexity
O(n) – To efficiently solve this problem without resorting to brute force, we use a hash map to group the indices of identical elements together and an auxiliary result array of size N to store the final distances. In the worst-case scenario where all elements in the input of size N are distinct, the hash map stores N keys and values, while the result array always holds N elements. Therefore, the total extra memory consumed scales linearly with the input size N, leading to an overall auxiliary space complexity of O(n).

Optimal Solution

Approach

Instead 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:

  1. Gather all the positions where each distinct item appears and keep them neatly separated by type.
  2. For each unique type of item, look at its list of positions from left to right.
  3. Instead of adding up every individual distance, calculate how much each position contributes to the total by seeing how far it is from all the positions that came before it and after it.
  4. Keep a running total of the positions you have already processed to easily figure out the distance to future positions without having to recalculate everything from scratch.
  5. Apply this running calculation to build the final answer for every single item in the original sequence.
  6. Combine all the results to get the complete picture of distances for the entire sequence efficiently.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – We iterate through the input array of size n once to group the positions of each identical element into separate lists. Next, we iterate through each unique element's position list to compute the distance contributions using a running sum of previous indices, taking linear time proportional to the total number of elements. Across all unique elements and their positions, every index is processed a constant number of times. This directly scales with the input size n without nested dependencies, resulting in O(n) total operations.
Space Complexity
O(n) – We utilize an auxiliary hash map to group the positions of each distinct item, along with an output array of size N to store the final distances. In the worst case where all elements are unique, the hash map stores N keys and N total index values. Additionally, a few primitive variables are used for running totals during the linear passes over these positions. Combining the hash map and the output array, the total auxiliary memory scales linearly with the input size N.

Edge Cases

Empty or single-element arrays
How to Handle:
Return an empty array or an array with a single zero since no identical element pairs exist.
Array with all identical elements
How to Handle:
Precompute total sums and use prefix sums to calculate absolute differences in O(1) time per element.
Array with all unique elements
How to Handle:
Return an array of all zeros since no element appears more than once.
Large input size up to one hundred thousand elements
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Ensure the index-grouping data structure efficiently scales without performance degradation from hash collisions.