The simplest approach is to concatenate all strings in each array into a single string, then compare the two resulting strings. If they match character by character, the arrays represent the same string.
word1 into a single string.word2 into a single string.true if they are equal, false otherwise.Where and are the total number of characters in both the arrays and , respectively.
We can reduce space usage by only concatenating one of the arrays. We then iterate through the second array character by character, comparing each character against the concatenated string. This way, we only build one full string instead of two.
word1 into a single string s1.i to 0.word2, then through each character in that string.s1's length or if the characters do not match.false immediately.word2, return true only if i equals the length of s1 (ensuring both have the same length).Where and are the total number of characters in both the arrays and , respectively.
We can avoid creating any concatenated strings by using four pointers: two to track which string we are currently in (one for each array), and two to track the character position within those strings. We compare characters one at a time, advancing through both arrays simultaneously.
w1 and w2 for the current word index in each array, i and j for the character position within the current words.false.0.true if both arrays are exhausted, false otherwise.class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
w1 = w2 = 0 # Index of word
i = j = 0 # Index of character
while w1 < len(word1) and w2 < len(word2):
if word1[w1][i] != word2[w2][j]:
return False
i, j = i + 1, j + 1
if i == len(word1[w1]):
w1 += 1
i = 0
if j == len(word2[w2]):
w2 += 1
j = 0
return w1 == len(word1) and w2 == len(word2)Where and are the total number of characters in both the arrays and , respectively.
When iterating through one array while comparing to the concatenated string of the other, returning true after matching all characters without verifying both strings have the same length. If word2 is shorter than word1, all characters may match but the strings are not equivalent.
# Wrong: missing final length check
return True
# Correct: verify all characters were consumed
return i == len(s1)Assuming arrays with the same number of elements will produce equivalent strings. The arrays ["ab", "c"] and ["a", "bc"] have different lengths but represent the same string "abc".