#2121

Intervals Between Identical Elements

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a HashMap to store indices of each unique value, allowing us to calculate the intervals in a single pass. This significantly reduces the number of operations needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a HashMap to store each unique value and its corresponding list of indices.
  2. 2Step 2: Iterate through the array and populate the HashMap with indices for each value.
  3. 3Step 3: For each unique value, calculate the total intervals using the stored indices by leveraging prefix sums to efficiently compute the distances.
solution.py28 lines
1# Full working Python code
2
3def sum_of_intervals(arr):
4    from collections import defaultdict
5    n = len(arr)
6    intervals = [0] * n
7    index_map = defaultdict(list)
8    for i in range(n):
9        index_map[arr[i]].append(i)
10    for indices in index_map.values():
11        total = 0
12        prefix_sum = 0
13        for i in range(len(indices)):
14            idx = indices[i]
15            total += idx * i - prefix_sum
16            intervals[idx] += total
17            prefix_sum += idx
18        total = 0
19        prefix_sum = 0
20        for i in range(len(indices) - 1, -1, -1):
21            idx = indices[i]
22            total += prefix_sum - idx * (len(indices) - 1 - i)
23            intervals[idx] += total
24            prefix_sum += idx
25    return intervals
26
27# Example usage
28print(sum_of_intervals([2,1,3,1,2,3,3]))

Complexity note: This complexity is achieved because we only traverse the array a few times, and the use of HashMap allows for efficient index storage and retrieval.

  • 1Using a HashMap to store indices allows for efficient retrieval and calculation.
  • 2Prefix sums help to compute intervals without redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.