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
Smallest Substring With Identical Characters II INPUT Binary String s = "1110" 1 i=0 1 i=1 1 i=2 0 i=3 Longest identical: "111" (len=3) Input Values s = "1110" numOps = 1 Goal Minimize longest identical substring using at most 1 flip ALGORITHM STEPS 1 Binary Search Search answer in [1, n] 2 Check Feasibility Can achieve len=mid? 3 Count Operations Flips needed for len 4 Optimal Pattern Try "0101" or "1010" For len=1 (alternating): 1 0 1 0 Target: "1010" needs 1 flip! Flips: "1110" to "1010" Only i=1 needs flip = 1 op FINAL RESULT Before (1 flip): 1 1 1 0 FLIP i=1 After: 1 0 1 0 Alternating: "1010" Max identical = 1 OUTPUT 1 Minimum length = 1 Key Insight: Binary search on the answer! For each candidate length L, check if we can make all identical substrings have length at most L using at most numOps flips. For L=1, the string must alternate. Count mismatches from "0101..." or "1010..." pattern. TutorialsPoint - Smallest Substring With Identical Characters II | Optimal Solution
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