Taro Logo

Longest Substring of One Repeating Character

#1 Most AskedHard
0 views
Topics:
ArraysStringsBinary Search

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.

Example 1:

Input: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]
Output: [3,3,4]
Explanation: 
- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.
- 2nd query updates s = "bbbccc". 
  The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.
- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.
Thus, we return [3,3,4].

Example 2:

Input: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]
Output: [2,3]
Explanation:
- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.
- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.
Thus, we return [2,3].

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
  • k == queryCharacters.length == queryIndices.length
  • 1 <= k <= 105
  • queryCharacters consists of lowercase English letters.
  • 0 <= queryIndices[i] < s.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string `s` (e.g., only lowercase English letters), and what are the maximum lengths of `s` and the query arrays?
  2. Can the query characters be identical to the characters already present at their respective indices, and how should we handle such redundant updates?
  3. What should the return format be? Is it a list of integers corresponding to the maximum repeating substring length after each individual query?
  4. Are the indices in the query array guaranteed to be valid and within the bounds of string `s`?
  5. How should we handle empty inputs, such as an empty string `s` or empty query arrays?

Brute Force Solution

Approach

This solution maintains information about contiguous blocks of identical characters using a segment tree. Each node in the segment tree tracks the maximum contiguous block within its range, as well as prefix and suffix contiguous blocks with their corresponding characters. Updates modify single leaf nodes in logarithmic time and push changes upward to dynamically maintain the global maximum.

Here's how the algorithm would work step-by-step:

  1. Initialize segment tree arrays to store maximum block lengths, prefix lengths, suffix lengths, segment sizes, and boundary characters.
  2. Implement the merge function to combine information from left and right children, checking if adjacent boundary characters can be merged.
  3. Construct the segment tree initially using the characters from the original string.
  4. Define the point-update function to change a character at a specified index and recalculate segment properties up to the root.
  5. Iterate through the queries, update the segment tree for each query, and collect the root node's maximum length.

Code Implementation

def longest_repeating(s: str, queryCharacters: str, queryIndices: list[int]) -> list[int]:
    string_length = len(s)
    tree_size = 4 * string_length
    max_length = [0] * tree_size
    prefix_length = [0] * tree_size
    suffix_length = [0] * tree_size
    prefix_char = [''] * tree_size
    suffix_char = [''] * tree_size
    length_of_segment = [0] * tree_size

    # Merge children information into parent node
    def push_up(node_index: int, left_child: int, right_child: int) -> None:
        length_of_segment[node_index] = length_of_segment[left_child] + length_of_segment[right_child]
        prefix_char[node_index] = prefix_char[left_child]
        suffix_char[node_index] = suffix_char[right_child]
        prefix_length[node_index] = prefix_length[left_child]
        suffix_length[node_index] = suffix_length[right_child]
        
        max_length[node_index] = max(max_length[left_child], max_length[right_child])
        if suffix_char[left_child] == prefix_char[right_child]:
            combined = suffix_length[left_child] + prefix_length[right_child]
            max_length[node_index] = max(max_length[node_index], combined)
            if prefix_length[left_child] == length_of_segment[left_child]:
                prefix_length[node_index] = length_of_segment[left_child] + prefix_length[right_child]
            if suffix_length[right_child] == length_of_segment[right_child]:
                suffix_length[node_index] = length_of_segment[right_child] + suffix_length[left_child]

    # Recursively build the initial segment tree
    def build(node_index: int, range_left: int, range_right: int) -> None:
        if range_left == range_right:
            current_char = s[range_left]
            length_of_segment[node_index] = 1
            max_length[node_index] = 1
            prefix_length[node_index] = 1
            suffix_length[node_index] = 1
            prefix_char[node_index] = current_char
            suffix_char[node_index] = current_char
            return
        mid_point = (range_left + range_right) // 2
        left_child = 2 * node_index
        right_child = 2 * node_index + 1
        build(left_child, range_left, mid_point)
        build(right_child, mid_point + 1, range_right)
        push_up(node_index, left_child, right_child)

    # Update a single position with the new character
    def update(node_index: int, range_left: int, range_right: int, target_index: int, new_char: str) -> None:
        if range_left == range_right:
            prefix_char[node_index] = new_char
            suffix_char[node_index] = new_char
            return
        mid_point = (range_left + range_right) // 2
        left_child = 2 * node_index
        right_child = 2 * node_index + 1
        if target_index <= mid_point:
            update(left_child, range_left, mid_point, target_index, new_char)
        else:
            update(right_child, mid_point + 1, range_right, target_index, new_char)
        push_up(node_index, left_child, right_child)

    build(1, 0, string_length - 1)
    query_count = len(queryIndices)
    answer_lengths = []
    # Process each query and store the maximum repeating length
    for query_idx in range(query_count):
        target_pos = queryIndices[query_idx]
        target_char = queryCharacters[query_idx]
        update(1, 0, string_length - 1, target_pos, target_char)
        answer_lengths.append(max_length[1])

    return answer_lengths

Big(O) Analysis

Time Complexity
O((n + k) * log n) – Building the segment tree takes O(n) time for a string of length n. Each of the k update queries traverses the tree from the root to a leaf and back, taking O(log n) time per query.
Space Complexity
O(n + k) – The segment tree arrays require O(n) space to store nodes, and the result array stores the answers for all k queries, taking O(k) space.

Optimal Solution

Approach

This problem requires maintaining the length of the longest homogeneous substring after point mutations. A segment tree is ideal because each node can maintain the longest repeating substring entirely within its interval, as well as the longest matching prefix and suffix. By combining information from adjacent intervals in constant time, each character update and global maximum retrieval can be performed in logarithmic time.

Here's how the algorithm would work step-by-step:

  1. Initialize segment tree arrays to store the prefix character, suffix character, prefix length, suffix length, and maximum homogeneous substring length for each node.
  2. Implement a merge function that combines child node attributes, bridging the boundary if the left child suffix character equals the right child prefix character.
  3. Build the segment tree over the initial string, populating base leaves and propagating values upward.
  4. For each query, update the target character in the segment tree at the specified index.
  5. Append the root maximum length to the result array after each query update and return the list of answers.

Code Implementation

def longest_repeating(s: str, queryCharacters: str, queryIndices: list[int]) -> list[int]:
    string_length = len(s)
    tree_size = 4 * string_length
    
    prefix_len = [0] * tree_size
    suffix_len = [0] * tree_size
    max_len = [0] * tree_size
    prefix_char = [''] * tree_size
    suffix_char = [''] * tree_size

    def pull(node: int, left_child: int, right_child: int, left_count: int, right_count: int):
        prefix_char[node] = prefix_char[left_child]
        suffix_char[node] = suffix_char[right_child]
        
        prefix_len[node] = prefix_len[left_child]
        if prefix_len[left_child] == left_count and suffix_char[left_child] == prefix_char[right_child]:
            prefix_len[node] += prefix_len[right_child]
            
        suffix_len[node] = suffix_len[right_child]
        if suffix_len[right_child] == right_count and suffix_char[left_child] == prefix_char[right_child]:
            suffix_len[node] += suffix_len[left_child]
            
        max_len[node] = max(max_len[left_child], max_len[right_child])
        if suffix_char[left_child] == prefix_char[right_child]:
            max_len[node] = max(max_len[node], suffix_len[left_child] + prefix_len[right_child])

    # Recursively builds the initial segment tree from the given string.
    def build_tree(node: int, start_idx: int, end_idx: int):
        if start_idx == end_idx:
            character = s[start_idx]
            prefix_char[node] = character
            suffix_char[node] = character
            prefix_len[node] = 1
            suffix_len[node] = 1
            max_len[node] = 1
            return
        mid_idx = (start_idx + end_idx) // 2
        left_child = 2 * node
        right_child = 2 * node + 1
        build_tree(left_child, start_idx, mid_idx)
        build_tree(right_child, mid_idx + 1, end_idx)
        pull(node, left_child, right_child, mid_idx - start_idx + 1, end_idx - mid_idx)

    # Updates a single position in the segment tree with the new character.
    def update_tree(node: int, start_idx: int, end_idx: int, target_idx: int, new_char: str):
        if start_idx == end_idx:
            prefix_char[node] = new_char
            suffix_char[node] = new_char
            prefix_len[node] = 1
            suffix_len[node] = 1
            max_len[node] = 1
            return
        mid_idx = (start_idx + end_idx) // 2
        left_child = 2 * node
        right_child = 2 * node + 1
        if target_idx <= mid_idx:
            update_tree(left_child, start_idx, mid_idx, target_idx, new_char)
        else:
            update_tree(right_child, mid_idx + 1, end_idx, target_idx, new_char)
        pull(node, left_child, right_child, mid_idx - start_idx + 1, end_idx - mid_idx)

    # Initialize segment tree over the input string.
    build_tree(1, 0, string_length - 1)
    
    answer = []
    # Process each query sequentially and record the maximum length.
    for query_char, query_idx in zip(queryCharacters, queryIndices):
        update_tree(1, 0, string_length - 1, query_idx, query_char)
        answer.append(max_len[1])
        
    return answer

Big(O) Analysis

Time Complexity
O((n + k) * log n) – Building the segment tree takes O(n) time for a string of length n. Each of the k queries requires updating a leaf node and recalculating values along the path to the root, taking O(log n) time per query.
Space Complexity
O(n + k) – The segment tree stores arrays of size proportional to 4n, and the result array stores k query outputs.

Edge Cases

String s with length of 1
How to Handle:
The segment tree or sliding window structure initializes correctly and returns 1 for the single query.
All characters in s are identical
How to Handle:
The range tracking structure maintains a single contiguous block equal to the length of s throughout all queries.
Query replaces a character with the exact same character it already has
How to Handle:
The update operation is treated as a no-op that efficiently bypasses structural tree modifications while still returning the correct maximum length.
Queries fragment a single large repeating substring into many isolated single characters
How to Handle:
The segment tree dynamically merges and splits interval properties to accurately reflect the collapsing maximum lengths.
Maximum length constraints where string length and query count are very large
How to Handle:
Using a segment tree with logarithmic time complexity per query ensures the solution scales efficiently within time limits.
Index out of bounds or invalid query indices
How to Handle:
Assuming standard well-formed competitive programming constraints where indices strictly fall within the range 0 to length of s minus 1.
0/1 completed