Taro Logo

Find Mismatched Segments Between Two Strings

Medium
Asked by:
Zoho
3 views
Topics:
ArraysStringsTwo Pointers

You are given two strings s1 and s2 of the same length.

A mismatched segment is a maximal contiguous range of indices where the characters of s1 and s2 differ at every index.

Return a 2D array containing [sub1, sub2] for each mismatched segment, where sub1 and sub2 are the corresponding substrings from s1 and s2, respectively. Return the segments in increasing order of their starting indices. If there are no mismatched segments, return an empty array.

Example 1:

Input: s1 = "earth", s2 = "empty"

Output: [["ar","mp"],["h","y"]]

Explanation:

  • The characters at indices 1 and 2 differ, forming the mismatched segment ["ar","mp"].
  • The characters at index 4 differ, forming the mismatched segment ["h","y"].

Example 2:

Input: s1 = "action", s2 = "nation"

Output: [["ac","na"]]

Explanation:

The characters at indices 0 and 1 differ, forming the mismatched segment ["ac","na"]. All remaining characters are equal in both strings.

Example 3:

Input: s1 = "hot", s2 = "hot"

Output: []

Explanation:

The two strings are identical, so there are no mismatched segments.

Constraints:

  • 1 <= s1.length == s2.length <= 100
  • s1 and s2 consist of lowercase English letters.

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 definition of a continuous segment—are they 0-indexed and inclusive of both start and end positions?
  2. What should be returned if the two strings are completely identical with no mismatches?
  3. What character set should we expect (e.g., standard ASCII, extended Unicode, case-sensitive)?
  4. Is it guaranteed that the input strings will always be of equal length?
  5. How should adjacent mismatched characters be grouped—do they form a single segment (e.g., indices 1 to 3) or separate single-character segments?

Brute Force Solution

Approach

To find all the mismatched parts between two texts, the brute force approach involves examining every single piece of both texts from beginning to end. By methodically comparing every possible section, we can spot and record every place where the two texts differ.

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

  1. Line up the two texts side by side so you can compare them directly from start to finish.
  2. Begin at the very first character of both texts and see if they match.
  3. If they do not match, mark this spot as the beginning of a mismatched section.
  4. Continue moving forward character by character, keeping track of whether the differences continue or if the texts start matching again.
  5. Whenever the texts start matching again after a difference, mark that point as the end of the mismatched section.
  6. Keep checking every remaining character until you reach the very end of both texts to ensure no differences are missed.
  7. Collect all the marked mismatched sections you found along the way and present them as the final result.

Code Implementation

def find_mismatched_segments(first_text, second_text):
    mismatched_segments = []
    current_index = 0
    text_length = max(len(first_text), len(second_text))

    # We scan character by character to detect where the two texts begin to diverge
    while current_index < text_length:
        if current_index >= len(first_text) or current_index >= len(second_text) or first_text[current_index] != second_text[current_index]:
            segment_start = current_index

            # We track the mismatch until characters match again to define the full boundary
            while current_index < text_length and (current_index >= len(first_text) or current_index >= len(second_text) or first_text[current_index] != second_text[current_index]):
                current_index += 1

            segment_end = current_index
            mismatched_segments.append((segment_start, segment_end))
        else:
            current_index += 1

    # We return all collected regions to provide a complete map of differences
    return mismatched_segments

Big(O) Analysis

Time Complexity
O(n) – To find all mismatched segments, we traverse both texts side by side from the very first character to the very end. The input size n is determined by the length of the texts, and the cost is driven by this single linear scan checking each character position once. This sequential traversal performs roughly n constant-time comparison operations from start to finish. Therefore, the total operations scale directly with the length of the strings, which simplifies to O(n).
Space Complexity
O(N) – To determine the auxiliary space complexity, we look at the result collection where N represents the total length of the input strings. The algorithm stores the identified mismatched sections in a dynamic list that acts as our output storage. In the worst-case scenario, where every single character alternates between matching and mismatching, the number of stored segments scales linearly with the input size N. Therefore, the extra memory required by this result collection is directly proportional to N, leading to a linear auxiliary space complexity.

Optimal Solution

Approach

To find all the mismatched parts between two texts efficiently, the optimal strategy walks through both texts side-by-side from start to finish. Instead of getting bogged down in messy details, it groups consecutive differences together into solid blocks of change as it moves along.

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

  1. Place the two texts side-by-side so you can examine them together from the very beginning to the very end.
  2. Walk through both texts in lockstep, comparing the characters at each position to see if they match.
  3. Whenever you encounter a character that does not match, recognize that you have stepped into a mismatched region and note where this difference begins.
  4. Keep walking forward together while the characters continue to mismatch, gathering the entire span of differing characters into a single segment.
  5. As soon as the characters match again, mark the end of the current mismatched segment and record it as a distinct difference.
  6. Resume walking forward together and repeat this process whenever another mismatch appears.
  7. Continue this journey until you reach the very end of both texts, ensuring you have successfully captured every single place where they differ.

Code Implementation

def find_mismatched_segments(first_text_string, second_text_string):
    mismatched_segments_list = []
    max_text_length = max(len(first_text_string), len(second_text_string))
    
    index_pointer = 0
    
    # We pad the strings with spaces to compare them evenly up to the maximum length.
    padded_first_text = first_text_string.ljust(max_text_length)
    
    padded_second_text = second_text_string.ljust(max_text_length)
    
    while index_pointer < max_text_length:
        if padded_first_text[index_pointer] != padded_second_text[index_pointer]:
            segment_start_index = index_pointer
            
            # We group consecutive mismatches into a single contiguous block of change.
            while index_pointer < max_text_length and padded_first_text[index_pointer] != padded_second_text[index_pointer]:
                index_pointer += 1
                
            segment_end_index = index_pointer
            
            mismatched_segments_list.append((segment_start_index, segment_end_index))
        else:
            index_pointer += 1
            
    # The final collected segments accurately capture every region of difference.
    return mismatched_segments_list

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single linear scan of both texts from start to finish. As we walk through the strings in lockstep, we compare characters at each position and group consecutive differences into segments. Because each character in the texts of combined length n is visited at most once during this traversal, the number of operations grows directly proportional to n. Summing these constant-time comparisons across the entire length of the texts yields approximately n operations, which simplifies to O(n).
Space Complexity
O(K) – To track the mismatched segments as we walk through the texts, we allocate an auxiliary list to store the resulting blocks of differences. In the worst-case scenario where alternating characters mismatch throughout the entire length, the number of stored segments scales proportionally with the input size N. Specifically, the extra memory used by this output list grows linearly relative to the number of mismatches K, where K is bounded by N. Therefore, simplifying this storage requirement for the collected segments yields a linear auxiliary space complexity.

Edge Cases

Empty strings or null inputs
How to Handle:
Return an empty list immediately after checking for null or zero-length inputs.
Strings of length one with a mismatch
How to Handle:
The linear scan correctly identifies the single character difference and returns a segment from index 0 to 0.
Strings with maximum allowed length
How to Handle:
An iterative single-pass approach processes the strings in linear time to avoid memory overflow or performance bottlenecks.
Strings that are completely identical
How to Handle:
The comparison loop completes without finding any discrepancies and returns an empty list.
Strings that differ at every single character
How to Handle:
The algorithm groups the entire length into one continuous segment spanning from the first to the last index.
Strings that differ only at the very first or very last character
How to Handle:
Boundary checks ensure that segments starting or ending at the extremes of the strings are captured accurately.
Strings with alternating matching and mismatching characters
How to Handle:
The state machine correctly opens and closes multiple single-character segments without missing adjacent boundaries.
Inputs with mixed case sensitivity or special Unicode characters
How to Handle:
Direct character code point comparison ensures accurate matching regardless of the underlying character set.