[LeetCode] Count Valid Prefixes

4006. Count Valid Prefixes

You are given a binary string s.

A prefix of s is considered valid if its characters can be rearranged to form an alternating string.

Return the number of valid prefixes of s.

A string is considered alternating if no two adjacent characters are equal.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int countValidPrefixes(string s) {
int res = 0, sum = 0;
for(auto& ch : s) {
sum += (ch == '0' ? -1 : 1);
if(abs(sum) <= 1) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/count-valid-prefixes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.