Try This Question
Before reading the solution, try solving the problem yourself on LeetCode:
👉 https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/
Problem Statement
You are given a binary string s consisting only of characters '0' and '1'.
In one operation, you can change any '0' to '1' or '1' to '0'.
A string is called alternating if no two adjacent characters are the same.
Example of Alternating Strings
Example of Non-Alternating Strings
Your task is to return the minimum number of operations required to make the string alternating.
Example Walkthrough
Example 1
Input
Possible fix:
Only the last character needs to change, so the answer is:
Output
Example 2
Input
The string is already alternating.
Output
Example 3
Input
Possible alternating strings:
Minimum operations needed = 2
Output
Key Observation
An alternating binary string can only have two possible patterns:
Pattern 1
Pattern 2
So instead of trying many combinations, we only need to check:
1️⃣ How many changes are required to convert s → "010101..."
2️⃣ How many changes are required to convert s → "101010..."
Then we return the minimum of the two.
Approach
Step 1
Generate two possible alternating strings:
Both will be of the same length as the input string.
Step 2
Compare the original string with both patterns.
Count mismatches.
For example:
Mismatch count = 1
Step 3
Repeat for the second pattern.
Finally return:
Intuition Behind the Solution
Instead of flipping characters randomly, we compare the string with the two valid alternating possibilities.
Why only two?
Because:
- Alternating strings must start with either 0 or 1
- After that, the pattern is fixed.
So we simply compute which pattern requires fewer changes.
This makes the solution efficient and simple.
Java Implementation
Complexity Analysis
Time Complexity
We iterate through the string a few times.
Space Complexity
Because we create two extra strings of size n.
Optimized Approach (Better Interview Answer)
We can avoid creating extra strings and calculate mismatches directly.
Optimized Java Code
Space Complexity Now
No extra strings required.
Why This Problem Is Important
This problem teaches important interview concepts:
✔ Pattern observation
✔ Greedy thinking
✔ String manipulation
✔ Optimization techniques
Many companies ask similar pattern-based string problems.
Final Thoughts
The trick in this problem is realizing that only two alternating patterns exist. Once you identify that, the problem becomes straightforward.
Instead of trying multiple modifications, you simply compare and count mismatches.
This leads to a clean and efficient O(n) solution.
If you are preparing for coding interviews, practicing problems like this will improve your pattern recognition skills, which is a key skill for solving medium and hard problems later.
Happy Coding 🚀




