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], where2 <= i <= n - 1.nums[i - 1] != nums[i], where1 <= 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code