Count Valid Prefixes Problem
#4006
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4006.
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.
Example 1:
Input: s = "00101"
Output: 3
Explanation:
The valid prefixes are:
- "0": It is already an alternating string.
- "001": It can be rearranged into "010", which is an alternating string.
- "00101": It can be rearranged into "01010", which is an alternating string.
Thus, the answer is 3.
Example 2:
Input: s = "101"
Output: 3
Explanation:
All prefixes of s = "101" are already alternating strings. Thus, the answer is 3.
Constraints:
1 <= s.length <= 100sconsists only of'0'and'1'.
Solution
Approach: Counting
A string can be rearranged into an alternating string exactly when its number of '0' and '1' characters differ by at most one.
Scan s once and keep t, the number of '1's minus the number of '0's in the current prefix. If |t| <= 1, the prefix is valid and we add one to the answer.
Complexity: time O(n), space O(1), where n is the length of s.
class Solution:
def countValidPrefixes(self, s: str) -> int:
ans = t = 0
for c in s:
t += 1 if c == '1' else -1
ans += 1 if abs(t) <= 1 else 0
return ans