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 Case
$ Input: nums = [3,1,3,2,4,3]
Output: 3
💡 Note: Need to make alternating pattern. Even positions (0,2,4) should have same value, odd positions (1,3,5) should have same value, and they must be different. Optimal: change indices 1,3,4 to get [3,2,3,2,3,2]
Example 2 — Already Alternating
$ Input: nums = [1,2,2,2,2]
Output: 2
💡 Note: Even positions (0,2,4): values [1,2,2]. Odd positions (1,3): values [2,2]. Best choice: Even=2, Odd=1. Change indices 0,1 to get [2,1,2,1,2]
Example 3 — Small Array
$ Input: nums = [1,2]
Output: 0
💡 Note: Already alternating since nums[0] ≠ nums[1]. No operations needed

Constraints

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

Visualization

Tap to expand
Make Array Alternating: [3,1,3,2,4,3]Goal: nums[i-2] == nums[i] and nums[i-1] != nums[i]313243012345Even positions: [3,3,4]Odd positions: [1,2,3]After optimization: Even=3, Odd=2323232Operations needed: 3 (change positions 1, 3, 4)
Understanding the Visualization
1
Input
Array [3,1,3,2,4,3] - not alternating
2
Pattern
Even positions must have same value, odd positions must have different value
3
Output
Minimum operations needed: 3
Key Takeaway
🎯 Key Insight: Split array into even/odd positions, find most frequent values for each group ensuring they differ
Asked in
Amazon 15 Google 12 Microsoft 8
28.0K 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