#2808
Minimum Seconds to Equalize a Circular Array
MediumArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach leverages the observation that we can minimize the number of seconds by focusing on the segments between occurrences of the same value. We only need to calculate the maximum distance between consecutive occurrences of the same value.
⚙️
Algorithm
3 steps- 1Step 1: Create a dictionary to store the indices of each unique value in the array.
- 2Step 2: For each unique value, calculate the maximum gap between consecutive indices to determine how many seconds are needed to fill the gaps.
- 3Step 3: Return the maximum of these values as the result.
solution.py16 lines
1# Full working Python code
2from collections import defaultdict
3
4def min_seconds(nums):
5 index_map = defaultdict(list)
6 for i, num in enumerate(nums):
7 index_map[num].append(i)
8 min_seconds = 0
9 n = len(nums)
10 for indices in index_map.values():
11 max_gap = 0
12 for j in range(1, len(indices)):
13 max_gap = max(max_gap, (indices[j] - indices[j - 1]) // 2)
14 max_gap = max(max_gap, (n - indices[-1] + indices[0]) // 2)
15 min_seconds = max(min_seconds, max_gap)
16 return min_secondsℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array to build the index map and then another pass through the unique values, which is efficient given the constraints.
- 1Understanding the circular nature of the array helps in calculating gaps correctly.
- 2Using a map to store indices allows us to efficiently calculate the required seconds.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.