Problem Description
Given a string s and k queries where each query updates the character at a specified index in s, return an array of k values such that the ith value is the length of the longest contiguous substring consisting of a single repeating character after performing the ith query.
Key Insights
- Only one character is updated per query, so only adjacent segments may need to be split or merged.
- It is efficient to represent s as a collection of segments, where each segment is a consecutive block of identical characters.
- An update may split an existing segment and then potentially merge with neighboring segments if they have the same character as the newly updated character.
- Data structures like balanced binary search trees or ordered sets can be leveraged to quickly identify and update segments.
- Alternatively, a direct simulation using a sorted list (or array) of segments is sufficient with proper binary search for locating the segment affected by each update.
Space and Time Complexity
Time Complexity: O((N + Q) log N) in the worst case, where N is the length of s and Q is the number of queries. Space Complexity: O(N) for storing the segments.
Solution
The solution creates segments representing blocks of identical characters. For every query:
- Find the segment that includes the update index.
- Remove that segment and split it into up to two segments if the update occurs in the middle.
- Insert a new segment at the updated position.
- Merge the new segment with adjacent segments if they contain the same character.
- Recalculate (or update) the longest segment length. This approach ensures that only segments possibly affected by the update are processed and merged, maintaining overall efficiency.