Talentd
FleetCode

3398. Smallest Substring With Identical Characters I

Hard21.0% acceptance2 companies

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 (where 0 <= i < n) and flip s[i]. If s[i] == '1', change s[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 <= 1000
  • s consists only of '0' and '1'.
  • 0 <= numOps <= n

Asked at 2 companies

Hints open one at a time

Hint 1
Can we use binary search here?
Hint 2
Use DP for predicate function
26:05
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minLength(self, s: str, numOps: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"000001"
1
Input
"0000"
2
Input
"0101"
0
Your code is saved on this device.Solution