Smallest Substring With Identical Characters II Problem
Description
LeetCode Problem 3399.
You are given a binary string s of length n and an integer numOps.
You are allowed to perform the following operation on s at most numOps times:
- Select any index
i(where0 <= i < n) and flips[i]. Ifs[i] == '1', changes[i]to'0'and vice versa.
You need to minimize the length of the longest substring of s such that all the characters in the substring are identical.
Return the minimum length after the operations.
Example 1:
Input: s = "000001", numOps = 1
Output: 2
Explanation:
By changing s[2] to '1', s becomes "001001". The longest substrings with identical characters are s[0..1] and s[3..4].
Example 2:
Input: s = "0000", numOps = 2
Output: 1
Explanation:
By changing s[0] and s[2] to '1', s becomes "1010".
Example 3:
Input: s = "0101", numOps = 0
Output: 1
Constraints:
1 <= n == s.length <= 10^5sconsists only of'0'and'1'.0 <= numOps <= n
Solution
Approach: Binary Search on the Answer
The longest run of equal characters can only get easier to bound as the limit m grows, so binary search m between 1 and n. Each check takes one pass over the string, which keeps the whole solution fast enough for n up to 10^5.
To check a candidate m we count the flips needed:
- For
m = 1the string must alternate (0101...or1010...). Count the positions that differ from the first pattern; the other pattern needsnminus that many. Take the smaller one. - For
m > 1, a run ofkequal characters needsk / (m + 1)flips (rounded down), because flipping every(m + 1)-th character breaks the run into pieces of length at mostm. Add this up over all runs.
m is feasible when the total is at most numOps. The answer is the smallest feasible m.
Complexity: O(n log n) time, O(1) extra space.
class Solution:
def minLength(self, s: str, numOps: int) -> int:
def check(m: int) -> bool:
cnt = 0
if m == 1:
t = "01"
cnt = sum(c == t[i & 1] for i, c in enumerate(s))
cnt = min(cnt, n - cnt)
else:
k = 0
for i, c in enumerate(s):
k += 1
if i == len(s) - 1 or c != s[i + 1]:
cnt += k // (m + 1)
k = 0
return cnt <= numOps
n = len(s)
l, r = 1, n
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l