Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 0-indexed array nums containing n integers.
At each second, you perform the following operation on the array:
i in the range [0, n - 1], replace nums[i] with either nums[i], nums[(i - 1 + n) % n], or nums[(i + 1) % n].Note that all the elements get replaced simultaneously.
Return the minimum number of seconds needed to make all elements in the array nums equal.
Example 1:
Input: nums = [1,2,1,2] Output: 1 Explanation: We can equalize the array in 1 second in the following way: - At 1st second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2]. It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
Example 2:
Input: nums = [2,1,3,3,2] Output: 2 Explanation: We can equalize the array in 2 seconds in the following way: - At 1st second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3]. - At 2nd second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3]. It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
Example 3:
Input: nums = [5,5,5,5] Output: 0 Explanation: We don't need to perform any operations as all elements in the initial array are the same.
Constraints:
1 <= n == nums.length <= 1051 <= nums[i] <= 109Problem summary: 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]. Note that all the elements get replaced simultaneously. Return the minimum number of seconds needed to make all elements in the array nums equal.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[1,2,1,2]
[2,1,3,3,2]
[5,5,5,5]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2808: Minimum Seconds to Equalize a Circular Array
class Solution {
public int minimumSeconds(List<Integer> nums) {
Map<Integer, List<Integer>> d = new HashMap<>();
int n = nums.size();
for (int i = 0; i < n; ++i) {
d.computeIfAbsent(nums.get(i), k -> new ArrayList<>()).add(i);
}
int ans = 1 << 30;
for (List<Integer> idx : d.values()) {
int m = idx.size();
int t = idx.get(0) + n - idx.get(m - 1);
for (int i = 1; i < m; ++i) {
t = Math.max(t, idx.get(i) - idx.get(i - 1));
}
ans = Math.min(ans, t / 2);
}
return ans;
}
}
// Accepted solution for LeetCode #2808: Minimum Seconds to Equalize a Circular Array
func minimumSeconds(nums []int) int {
d := map[int][]int{}
for i, x := range nums {
d[x] = append(d[x], i)
}
ans := 1 << 30
n := len(nums)
for _, idx := range d {
m := len(idx)
t := idx[0] + n - idx[m-1]
for i := 1; i < m; i++ {
t = max(t, idx[i]-idx[i-1])
}
ans = min(ans, t/2)
}
return ans
}
# Accepted solution for LeetCode #2808: Minimum Seconds to Equalize a Circular Array
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 ans
// Accepted solution for LeetCode #2808: Minimum Seconds to Equalize a Circular Array
/**
* [2808] Minimum Seconds to Equalize a Circular Array
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
impl Solution {
pub fn minimum_seconds(nums: Vec<i32>) -> i32 {
let mut map = HashMap::new();
for (index, num) in nums.iter().enumerate() {
let entry = map.entry(*num).or_insert(Vec::new());
entry.push(index);
}
let mut result = i32::MAX;
for (_, pos) in map {
let mut max_distance = pos[0] + nums.len() - pos.last().unwrap();
for i in 1..pos.len() {
max_distance = max_distance.max(pos[i] - pos[i - 1]);
}
result = result.min(max_distance as i32 / 2);
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2808() {
assert_eq!(Solution::minimum_seconds(vec![1, 2, 1, 2]), 1);
assert_eq!(Solution::minimum_seconds(vec![2, 1, 3, 3, 2]), 2);
}
}
// Accepted solution for LeetCode #2808: Minimum Seconds to Equalize a Circular Array
function minimumSeconds(nums: number[]): number {
const d: Map<number, number[]> = new Map();
const n = nums.length;
for (let i = 0; i < n; ++i) {
if (!d.has(nums[i])) {
d.set(nums[i], []);
}
d.get(nums[i])!.push(i);
}
let ans = 1 << 30;
for (const [_, idx] of d) {
const m = idx.length;
let t = idx[0] + n - idx[m - 1];
for (let i = 1; i < m; ++i) {
t = Math.max(t, idx[i] - idx[i - 1]);
}
ans = Math.min(ans, t >> 1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.