Smallest Substring With Identical Characters II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "1110", numOps = 1
Output: 1
💡 Note: We can flip s[1] to get "1010". The longest identical substring is now "1" with length 1, which is the minimum possible.
Example 2 — Multiple Operations
$ Input: s = "000111", numOps = 2
Output: 2
💡 Note: We can flip positions 1 and 4 to get "010101". Now the longest identical substring has length 1. Or flip position 2 to get "001111" then position 5 to get "001110", giving max length 2.
Example 3 — No Operations Needed
$ Input: s = "101", numOps = 1
Output: 1
💡 Note: The string already has max identical substring length 1, so no operations are needed.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of '0' and '1'
  • 0 ≤ numOps ≤ s.length

Visualization

Tap to expand
Minimize Longest Identical SubstringInput: s = "1110", numOps = 111100123Length 3 identical substringAfter flipping s[1]: "1010"1010Max identical length = 1Optimal strategy: Create alternating pattern to minimize runs
Understanding the Visualization
1
Input
Binary string with allowed flips
2
Process
Find optimal flips to minimize max identical length
3
Output
Minimum possible max identical substring length
Key Takeaway
🎯 Key Insight: Binary search on the answer - if we can achieve max length k, we can achieve any length > k
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
15.4K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen