Smallest Substring With Identical Characters I Problem
#3398
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 3398.
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 <= 1000sconsists only of'0'and'1'.0 <= numOps <= n
Solution
Approach: Binary Search on the Answer
If the longest run of equal characters can be made at most m, it can also be made at most m + 1, so we can binary search m between 1 and n.
To check a candidate m we count the flips needed:
- For
m = 1the string must alternate, so it ends up as0101...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), since one flip placed after everymcharacters splits it 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