Intuition
Any beautiful string splits into blocks of exactly two equal characters, so scan the string two at a time and fix each mismatched pair with one change.
Explanation
Key observation
A beautiful string is partitioned into even-length blocks, each made of a single repeated character. The simplification is that we can always use blocks of length exactly 2. Any even-length block of the same character (say 0000) can be cut into size-2 blocks (00 + 00) that are still valid. So instead of worrying about every possible partition, we only ever need to look at the string as a sequence of fixed, non-overlapping pairs: positions (0,1), (2,3), (4,5), and so on.
The rule for one pair
For a pair to be a valid size-2 block, its two characters must be equal. If they already match (00 or 11), it costs nothing. If they differ (01 or 10), we must change exactly one of the two characters to make them equal, so each mismatched pair costs one change. These pairs are independent, so the total is the number of mismatched pairs.
Walk-through with s = "100100"
Split into fixed pairs and check each:
"10"(positions 0,1): the characters differ, so this block needs 1 change. Running total: 1."01"(positions 2,3): the characters differ, so this block needs 1 change. Running total: 2."00"(positions 4,5): both characters match, so this block is already fine. Running total: 2.
Two of the three pairs are mismatched, so the answer is 2.
Why this is optimal
Because the size-2 blocks are disjoint and cover the whole string, no change can fix two blocks at once. Each mismatched pair requires its own change, and one change is always enough to equalise a pair. Counting mismatched pairs therefore gives the exact minimum.
Complexity
- Time: O(n). A single pass over the string, stepping two characters at a time.
- Space: O(1). Only a running counter is kept.
Implementation
class Solution {
public int minChanges(String s) {
int changes = 0;
for (int i = 0; i < s.length(); i += 2) {
if (s.charAt(i) != s.charAt(i + 1)) {
changes++;
}
}
return changes;
}
}