Longest Substring of One Repeating Character - Problem

You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries.

The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i].

Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.

Input & Output

Example 1 — Basic Updates
$ Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]
Output: [3,3,4]
💡 Note: Query 1: s="baaacc" → longest "aaa" = 3. Query 2: s="babcc" → longest "cc" or "bb" = 3. Query 3: s="babbc" → longest "bbb" = 4.
Example 2 — Single Character
$ Input: s = "abcd", queryCharacters = "aa", queryIndices = [0,1]
Output: [1,2]
💡 Note: Query 1: s="aacd" → longest single chars = 1. Query 2: s="aacd" → longest "aa" = 2.
Example 3 — All Same
$ Input: s = "aa", queryCharacters = "a", queryIndices = [0]
Output: [2]
💡 Note: Query 1: s="aa" → longest "aa" = 2 (no change in this case).

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters
  • 1 ≤ k ≤ 105
  • 0 ≤ queryIndices[i] < s.length
  • queryCharacters[i] is a lowercase English letter

Visualization

Tap to expand
Longest Substring of One Repeating CharacterInput:s = "babacc", queries = [(1,'b'),(3,'c'),(3,'b')]babaccProcess:Query 1: s[1]='b' → "bbbacc" → max length = 3Query 2: s[3]='c' → "bbbccc" → max length = 3Query 3: s[3]='b' → "bbbbcc" → max length = 4Output:[3, 3, 4]
Understanding the Visualization
1
Input
String s with query characters and indices
2
Process
Update character and find longest repeating substring
3
Output
Array of lengths after each query
Key Takeaway
🎯 Key Insight: Track character segments and update only affected boundaries to avoid full string scans
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
25.0K Views
Medium Frequency
~35 min Avg. Time
850 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