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 Character INPUT String s = "babacc" b 0 a 1 b 2 a 3 c 4 c 5 queryCharacters = "bcb" b c b queryIndices = [1,3,3] 1 3 3 3 queries to process Each updates string at given index with new char ALGORITHM STEPS 1 Query 1: s[1]='b' "babacc" --> "bbbacc" b b b a c c = 3 2 Query 2: s[3]='c' "bbbacc" --> "bbbccc" b b b c c c = 3 3 Query 3: s[3]='b' "bbbccc" --> "bbbbcc" b b b b c c = 4 4 Segment Tracking Use segment tree to track longest segment after each update FINAL RESULT Output Array: lengths 3 3 4 [0] [1] [2] Results Breakdown: Query 1: "bbbacc" --> max=3 (bbb) Query 2: "bbbccc" --> max=3 (both) Query 3: "bbbbcc" --> max=4 (bbbb) OK - [3, 3, 4] Key Insight: Use a Segment Tree to efficiently track and merge consecutive character segments. Each node stores: longest prefix, suffix, and overall substring of same character. Update takes O(log n) time, making total complexity O(k * log n) for k queries. TutorialsPoint - Longest Substring of One Repeating Character | Segment Tracking Approach
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