The problem: given two string arrays word1 and word2, return true if concatenating each array's strings in order gives the same string. Example: ["ab", "c"] and ["a", "bc"] both spell "abc", so the answer is true.
Version 1: just join
def arrayStringsAreEqual(word1, word2):
return "".join(word1) == "".join(word2)
Correct and readable. Cost: O(n) time, but also O(n) extra space, because both full strings are built before comparing. Say that out loud; it is exactly what sets up the follow-up.
Version 2: four indices, O(1) extra space
Keep a pointer to the current word and the current character inside it, for each array.
def arrayStringsAreEqual(word1, word2):
i = j = 0 # which word
a = b = 0 # which char inside that word
while i < len(word1) and j < len(word2):
if word1[i][a] != word2[j][b]:
return False
a += 1
b += 1
if a == len(word1[i]):
i, a = i + 1, 0
if b == len(word2[j]):
j, b = j + 1, 0
return i == len(word1) and j == len(word2)
The final check matters: if one array runs out first, the strings have different lengths. Empty strings inside an array are allowed by some variants, so if you want to be safe, skip words of length 0 before indexing.
Version 3: generators
In Python you can flatten lazily and compare character streams:
from itertools import chain, zip_longest
def arrayStringsAreEqual(word1, word2):
s1, s2 = chain.from_iterable(word1), chain.from_iterable(word2)
return all(x == y for x, y in zip_longest(s1, s2))
zip_longest pads with None, so unequal lengths fail automatically.
What the interviewer is checking
Whether you notice the hidden allocation in the one-liner, and whether you can manage two nested cursors without off-by-one errors. The same pattern shows up in merging iterators and comparing chunked network buffers.
I help build AI tool for job interviews at Linkjob AI, which helps you practise explaining solutions like this in real time. (Disclosure: affiliated.)