Minimum Changes To Make Alternating Binary String
Minimum Changes To Make Alternating Binary String is a easy arrays & hashing problem solved with the string basics pattern.
The best approach, optimal (count one pattern, derive the other), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (build both targets) up.
Problem
You are given a string s made of the characters '0' and '1'. In one operation you may change any single character from '0' to '1' or from '1' to '0'.
A string is alternating when no two neighbouring characters are equal, like "0101" or "10101". Return the minimum number of operations needed to make s alternating.
Examples
Example 1
- Input
s = "1101"- Output
1- Why
- Changing the first character gives "0101", which alternates, so one change is enough.
Example 2
- Input
s = "000"- Output
1- Why
- Flip the middle character to get "010".
Example 3
- Input
s = "10"- Output
0- Why
- The string already alternates.
Constraints
1 <= s.length <= 10^4s[i]is'0'or'1'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (build both targets) | O(n) | O(n) |
| Optimal (count one pattern, derive the other) | O(n) | O(1) |
1Brute force (build both targets)
O(n)Two linear builds and two linear comparisons.O(n)Two extra strings of length n.Build the two alternating strings of the same length, one starting with '0' and one with '1', compare each with s character by character, and return the smaller number of differences.
- Build
a = "0101…"andb = "1010…"of length n. - Count positions where
sdiffers froma, and where it differs fromb. - Return the smaller count.
class Solution {
public int minOperations(String s) {
int n = s.length();
StringBuilder a = new StringBuilder(), b = new StringBuilder();
for (int i = 0; i < n; i++) {
a.append(i % 2 == 0 ? '0' : '1');
b.append(i % 2 == 0 ? '1' : '0');
}
int da = 0, db = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) != a.charAt(i)) da++;
if (s.charAt(i) != b.charAt(i)) db++;
}
return Math.min(da, db);
}
}class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
a = "".join('0' if i % 2 == 0 else '1' for i in range(n))
b = "".join('1' if i % 2 == 0 else '0' for i in range(n))
da = sum(1 for i in range(n) if s[i] != a[i])
db = sum(1 for i in range(n) if s[i] != b[i])
return min(da, db)class Solution {
public:
int minOperations(string s) {
int n = s.size();
string a, b;
for (int i = 0; i < n; i++) {
a.push_back(i % 2 == 0 ? '0' : '1');
b.push_back(i % 2 == 0 ? '1' : '0');
}
int da = 0, db = 0;
for (int i = 0; i < n; i++) {
if (s[i] != a[i]) da++;
if (s[i] != b[i]) db++;
}
return min(da, db);
}
};function minOperations(s) {
const n = s.length;
let a = "", b = "";
for (let i = 0; i < n; i++) {
a += i % 2 === 0 ? '0' : '1';
b += i % 2 === 0 ? '1' : '0';
}
let da = 0, db = 0;
for (let i = 0; i < n; i++) {
if (s[i] !== a[i]) da++;
if (s[i] !== b[i]) db++;
}
return Math.min(da, db);
}2Optimal (count one pattern, derive the other)
O(n)One pass over the string.O(1)A single counter.Every position mismatches exactly one of the two patterns. So if s differs from "0101…" in c positions, it differs from "1010…" in n - c positions, and the answer is min(c, n - c).
- c = number of i where
s[i] - '0' != i % 2. - Return
min(c, n - c).
class Solution {
public int minOperations(String s) {
int n = s.length(), c = 0;
for (int i = 0; i < n; i++)
if (s.charAt(i) - '0' != i % 2) c++;
return Math.min(c, n - c);
}
}class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
c = sum(1 for i, ch in enumerate(s) if int(ch) != i % 2)
return min(c, n - c)class Solution {
public:
int minOperations(string s) {
int n = s.size(), c = 0;
for (int i = 0; i < n; i++)
if (s[i] - '0' != i % 2) c++;
return min(c, n - c);
}
};function minOperations(s) {
const n = s.length;
let c = 0;
for (let i = 0; i < n; i++)
if (s.charCodeAt(i) - 48 !== i % 2) c++;
return Math.min(c, n - c);
}Edge cases to test
- Length 1 (always 0 changes)
- Already alternating, starting with either digit
- All characters equal
- Odd length, where the two patterns need different numbers of each digit
Hints
Hint 1
An alternating string of length n is fully determined by its first character, so there are only two candidates.
Hint 2
If the string differs from "0101…" in c places, how many places does it differ from "1010…"?
FAQ
What is the best time complexity for Minimum Changes To Make Alternating Binary String?
Optimal (count one pattern, derive the other) runs in O(n) time and O(1) extra space. One pass over the string.
Which pattern does Minimum Changes To Make Alternating Binary String use?
It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Rotate String.
Is there a brute force solution for Minimum Changes To Make Alternating Binary String?
Yes. Brute force (build both targets) takes O(n) time and O(n) space. Build the two alternating strings of the same length, one starting with '0' and one with '1', compare each with s character by character, and return the smaller number of differences.
Which edge cases should I test for Minimum Changes To Make Alternating Binary String?
Length 1 (always 0 changes); Already alternating, starting with either digit; All characters equal; Odd length, where the two patterns need different numbers of each digit.