Find Mismatched Segments Between Two Strings Problem
Description
LeetCode Problem 4106.
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 <= 100s1ands2consist of lowercase English letters.
Solution
Approach: Two Pointers
Scan both strings from left to right with an index i. If s1[i] == s2[i], move on. Otherwise start a segment at i, set j = i + 1, and move j right while s1[j] != s2[j]. All indices in [i, j) differ, and the segment is maximal because the character before i matches (or i = 0) and the character at j matches (or j = n). Add [s1[i..j), s2[i..j)] to the answer and continue from j.
Complexity: O(n) time, and O(1) extra space besides the answer.
class Solution:
def findMismatchedSegments(self, s1: str, s2: str) -> List[List[str]]:
ans = []
n = len(s1)
i = 0
while i < n:
if s1[i] == s2[i]:
i += 1
continue
j = i + 1
while j < n and s1[j] != s2[j]:
j += 1
ans.append([s1[i:j], s2[i:j]])
i = j
return ans