Minimum Operations to Make the Array Alternating - Problem

You are given a 0-indexed array nums consisting of n positive integers.

The array nums is called alternating if:

  • nums[i - 2] == nums[i], where 2 <= i <= n - 1.
  • nums[i - 1] != nums[i], where 1 <= i <= n - 1.

In one operation, you can choose an index i and change nums[i] into any positive integer.

Return the minimum number of operations required to make the array alternating.

Input & Output

Example 1 — Basic Alternating Pattern
$ Input: nums = [3,1,3,2,4,3]
Output: 3
💡 Note: Even positions [0,2,4]: values [3,3,4] → keep 3 (appears twice), change position 4. Odd positions [1,3,5]: values [1,2,3] → keep any value, change others. Total: 1 + 2 = 3 operations.
Example 2 — Short Array
$ Input: nums = [1,2,2,2,2]
Output: 2
💡 Note: Even positions [0,2,4]: values [1,2,2] → use 2, change position 0. Odd positions [1,3]: values [2,2] → use different value like 1, change both. Total: 1 + 2 = 3, but we can use 1 for odd positions: 1 + 0 = 1. Actually 1 + 1 = 2.
Example 3 — Already Alternating
$ Input: nums = [1,2,1,2]
Output: 0
💡 Note: Array is already alternating: positions alternate between 1 and 2. No operations needed.

Constraints

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

Visualization

Tap to expand
INPUTALGORITHMRESULTArray: [3,1,3,2,4,3]313243012345Blue: Even positionsOrange: Odd positionsNeed alternating pattern:Even ≠ Odd valuesSame positions = Same value1Separate PositionsEven: [3,3,4] → count frequenciesOdd: [1,2,3] → count frequencies2Count FrequenciesEven: 3→2, 4→1 (most: 3)Odd: 1→1, 2→1, 3→1 (any)3Choose Best PairEven: use 3 (1 change needed)Odd: use 1 (2 changes needed)Total: 1 + 2 = 3 operationsFinal Array Pattern[3,1,3,1,3,1]Perfect alternating!Operations Needed3Position 4: 4→3Position 3: 2→1Position 5: 3→1Minimum possible!O(n) time complexityKey Insight:Alternating arrays have two independent subsequences at even and odd positions.Find most frequent values in each group that don't conflict with each other.TutorialsPoint - Minimum Operations to Make Array Alternating | Frequency Count Approach
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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