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
Smallest Substring With Identical Characters INPUT Binary String s: 1 1 1 0 0 0 1 2 3 4 Input Values: s = "11100" numOps = 1 Current longest identical: "111" (length 3) GREEDY ALGORITHM 1 Find Identical Runs Scan string for groups 111 (3) 00 (2) 2 Target Longest Run Focus on "111" (len=3) 3 Apply Flip Operation Flip s[1]: '1' to '0' 1 0 1 0 0 4 Check New Max Result: "10100" Runs: 1,0,1,00 Max length = 2 FINAL RESULT Before Operation: 1 1 1 0 0 Max identical = 3 After 1 Flip (index 1): 1 0 1 0 0 Max identical = 2 OUTPUT 2 Minimum longest substring with identical chars: OK Key Insight: The greedy approach targets the longest run of identical characters. By flipping a character in the middle of the longest run, we split it into smaller segments. With numOps=1, we can reduce "111" (length 3) to maximum "00" (length 2), achieving the optimal minimum longest identical substring length. TutorialsPoint - Smallest Substring With Identical Characters I | Greedy Approach
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