Minimum Seconds to Equalize a Circular Array — LeetCode 2808 Python Solution
- Problem
- #2808
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array nums containing n integers. At each second, you perform the following operation on the array: For every index i in the range [0, n - 1], replace nums[i] with either nums[i], nums[(i - 1 + n) % n], or nums[(i + 1) % n].
Example
- Input
- nums = [1,2,1,2]
- Output
- 1
- Explanation
- We can equalize the array in 1 second in the following way:
Python solution
class Solution:
def minimumSeconds(self, nums: List[int]) -> int:
d = defaultdict(list)
for i, x in enumerate(nums):
d[x].append(i)
ans = inf
n = len(nums)
for idx in d.values():
t = idx[0] + n - idx[-1]
for i, j in pairwise(idx):
t = max(t, j - i)
ans = min(ans, t // 2)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2808. Minimum Seconds to Equalize a Circular Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2808. Minimum Seconds to Equalize a Circular Array?
- LeetCode 2808. Minimum Seconds to Equalize a Circular Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2808. Minimum Seconds to Equalize a Circular Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2808. Minimum Seconds to Equalize a Circular Array?
- The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 2808. Minimum Seconds to Equalize a Circular Array cover?
- LeetCode 2808. Minimum Seconds to Equalize a Circular Array is tagged Array and Hash Table on LeetCode.