Minimum Seconds to Equalize a Circular Array - 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].

Note that all the elements get replaced simultaneously.

Return the minimum number of seconds needed to make all elements in the array nums equal.

Input & Output

Example 1 — Mixed Values
$ Input: nums = [1,2,1,3,1]
Output: 1
💡 Note: Value 1 is at positions [0,2,4]. It can spread to adjacent positions in 1 second, covering the entire array fastest.
Example 2 — Two Values
$ Input: nums = [2,1,1,2]
Output: 1
💡 Note: Both values 1 and 2 are well distributed. Each takes 1 second to spread completely.
Example 3 — All Same
$ Input: nums = [5,5,5,5]
Output: 0
💡 Note: All elements are already equal, no spreading needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Seconds to Equalize Circular Array INPUT 1 2 1 3 1 i=0 i=1 i=2 i=3 i=4 nums = [1, 2, 1, 3, 1] n = 5 (circular) Each second: element can copy from neighbor or stay All changes simultaneous ALGORITHM STEPS 1 Group by Value Store indices for each value 1 --> [0, 2, 4] 2 --> [1] 3 --> [3] 2 Calculate Max Gap Find largest gap between same values (circular) 3 Seconds = Gap / 2 Value spreads from both sides toward middle 4 Find Minimum Best value = smallest max gap Value 1: gaps [2,2,1] max=2 Seconds = 2/2 = 1 Value 2: gap=5, sec=2 Value 3: gap=5, sec=2 FINAL RESULT Initial State (t=0) [1, 2, 1, 3, 1] 1 sec After 1 Second (t=1) [1, 1, 1, 1, 1] How 1 spreads: i=1: copies from i=0 or i=2 i=3: copies from i=2 or i=4 All positions become 1 simultaneously! OUTPUT 1 Key Insight: For value v at indices [i1, i2, ...], the time to fill the largest gap is (max_gap / 2) rounded up. Values spread simultaneously from both directions, meeting in the middle of each gap. The optimal answer is the minimum over all values. Value 1 has max gap 2, needing only 1 second. TutorialsPoint - Minimum Seconds to Equalize a Circular Array | Optimized Distance Calculation
Asked in
Google 25 Meta 20 Amazon 15
29.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen