Skip to main content
Back to problems
#2808
Medium Algorithms

Minimum seconds to equalize a circular array

Array Hash Table
28.5% acceptance
Feb 25, 2026
549
32
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_seconds(nums: Vec<i32>) -> i32 {
    use std::collections::HashMap;
    let n = nums.len();
    let mut pos: HashMap<i32, Vec<usize>> = HashMap::new();
    for (i, &v) in nums.iter().enumerate() { pos.entry(v).or_default().push(i); }
    let mut ans = n;
    for indices in pos.values() {
      let m = indices.len();
      let mut max_gap = 0usize;
      for i in 0..m {
        let gap = if i + 1 < m { indices[i+1] - indices[i] } else { n - indices[m-1] + indices[0] };
        max_gap = max_gap.max(gap);
      }
      ans = ans.min(max_gap / 2);
    }
    ans as i32
  }
}