How would you like to learn today? Visualize algorithms in real time, explore them step by step through reading, or challenge yourself with a test.
Visualize the algorithm step-by-step with interactive animations. See exactly how the code executes in real time.
Read comprehensive problem explanation, reference links, and explore the code at your own pace.
Drag and arrange the algorithm steps in the correct execution order.
Difficulty: š¢ Easy
Topics: String, Greedy
You are given a binary string s consisting only of characters:
'0''1'In one operation, you can change:
'0' ā '1''1' ā '0'A string is called alternating if no two adjacent characters are equal.
ā Example of alternating string:
"010"
"1010"
ā Not alternating:
"0100"
"1111"
Return the minimum number of operations required to make the string alternating.
Input: s = "0100"
Output: 1
š” Explanation:
Change last character to '1' ā "0101"
Now the string is alternating.
Input: s = "10"
Output: 0
š” Explanation:
Already alternating. No changes needed.
Input: s = "1111"
Output: 2
š” Explanation:
You can convert it to:
"0101""1010"Minimum 2 operations required.
1 <= s.length <= 10^4s[i] is either '0' or '1'There are only two possible alternating patterns:
'0' ā "010101..."'1' ā "101010..."Count mismatches with both patterns and return the minimum.
⨠Perfect for practicing Greedy + String manipulation!
public class Main {
public static int minOperations(String s) {
int startWithZero = 0; // Pattern: 010101...
int startWithOne = 0; // Pattern: 101010...
for (int i = 0; i < s.length(); i++) {
// Expected characters
char expectedZero = (i % 2 == 0) ? '0' : '1';
char expectedOne = (i % 2 == 0) ? '1' : '0';
if (s.charAt(i) != expectedZero) {
startWithZero++;
}
if (s.charAt(i) != expectedOne) {
startWithOne++;
}
}
return Math.min(startWithZero, startWithOne);
}
public static void main(String[] args) {
// Hardcoded Input
String s = "1111";
int result = minOperations(s);
System.out.println("Input: " + s);
System.out.println("Minimum Operations Required: " + result);
}
}
O(n)
O(1)
⨠Clean Greedy approach
⨠Only single pass required
⨠Perfect for String pattern understanding
Follow every state change, comparison, and transformation as the execution unfolds in real time, so you understand not just the result, but the journey.
The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.
Understand Below AlgorithmGreen text means the instruction is placed in the correct position.
Red text means the instruction is in the wrong position.
Instructions with the same background color indicate particular blocks start and end.
A tick mark means the instruction is correct and locked.
š Locked steps cannot be moved. Only unlocked steps are draggable.
š Enable sound for swap feedback and completion effects.
Ā© 2026 | Privacy Policy | About