Smallest Substring With Identical Characters I - 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 = "11100", numOps = 1
Output: 2
💡 Note: We can flip position 2 (0-indexed) to get "11000". The longest identical substring has length 2 (either "11" or "00").
Example 2 — No Operations Needed
$ Input: s = "10101", numOps = 2
Output: 1
💡 Note: The string already alternates, so the longest identical substring is 1. No operations needed.
Example 3 — All Same Characters
$ Input: s = "1111", numOps = 1
Output: 2
💡 Note: We can flip any position to get something like "1011". The longest identical substring becomes 2.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ numOps ≤ n
  • s consists only of '0' and '1'

Visualization

Tap to expand
Minimize Maximum Identical Substring LengthInput: s = "11100", numOps = 111100Current max substring length: 3 ("111")Flip position 2: 111 → 11011000Result: Maximum substring length = 2"11" and "000" are the longest identical substrings
Understanding the Visualization
1
Input
Binary string "11100" with 1 operation allowed
2
Process
Strategically flip bits to break long identical segments
3
Output
Minimum possible maximum substring length: 2
Key Takeaway
🎯 Key Insight: Use binary search on the answer space to efficiently find the minimum achievable maximum substring length
Asked in
Google 15 Microsoft 12 Amazon 8
5.6K Views
Medium Frequency
~35 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