Given two string arrays, word1 and word2, you need to determine if they represent the same string. For example, if word1 = ["ab", "c"] and word2 = ["a", "bc"], both represent the concatenated string "abc", so they are equivalent.
This is a popular "Easy" question at Apple, Amazon, and Google. It tests your basic string manipulation skills and your ability to optimize for space. While the "naive" solution is to concatenate both arrays and compare the resulting strings, a more advanced solution uses pointers to compare characters one by one without creating new large strings.
The pattern is Two Pointers. You maintain four indices: i1 and i2 for the current word in each array, and p1 and p2 for the current character within those words. You compare word1[i1][p1] with word2[i2][p2]. If they match, you increment the character pointers. If a word is finished, you move to the next word in that array and reset the character pointer.
word1 = ["ab", "c"], word2 = ["a", "bc"]
word1[0][0] ('a') and word2[0][0] ('a'). Match!word2[0] is finished. Move to word2[1].word1[0][1] ('b') and word2[1][0] ('b'). Match!word1[0] is finished. Move to word1[1].word1[1][0] ('c') and word2[1][1] ('c'). Match!
Both arrays are finished at the same time. Result: True.The biggest mistake is using string concatenation ("".join(word1)), which uses extra space. In an interview, the goal is often to see if you can achieve extra space using pointers. Another error is not checking if both arrays finish at the same time; if one array has extra characters at the end, they are not equivalent.
Practice "in-place" comparisons whenever possible. Many string and array problems have a simple space solution and a slightly harder space solution. Interviewers highly value the latter.