Problem
Given two string arrays word1
and word2
, return true
if the two arrays represent the same string, and false
otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
Examples
Example 1:
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
Explanation:
word1 represents string "ab" + "c" -> "abc"
word2 represents string "a" + "bc" -> "abc"
The strings are the same, so return true.
Example 2:
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false
Example 3:
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
Output: true
Solution
Method 1 - Concatenate the words
To check if the concatenated strings formed from word1
and word2
are the same, we have two straightforward approaches:
- Concatenate all elements of
word1
andword2
and directly compare the resulting strings. - Compare the elements of
word1
andword2
without creating the complete concatenated strings, ensuring they match character by character.
Code
Java
public class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String w : word1) {
sb1.append(w);
}
for (String w : word2) {
sb2.append(w);
}
return sb1.toString().equals(sb2.toString());
}
}
Python
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
return ''.join(word1) == ''.join(word2)
Complexity
- ⏰ Time complexity:
O(n + m)
, wheren
andm
are the total lengths of the strings inword1
andword2
, respectively. - 🧺 Space complexity:
O(n + m)
due to storing the concatenated strings.
Method 2 - Compare characters directly
Instead of concatenating the arrays and then comparing the resulting strings, we can directly compare the characters of both the arrays.
Code
Java
public class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
int i = 0, j = 0, w1 = 0, w2 = 0;
while (w1 < word1.length && w2 < word2.length) {
if (word1[w1].charAt(i) != word2[w2].charAt(j)) {
return false;
}
if (++i == word1[w1].length()) {
i = 0;
w1++;
}
if (++j == word2[w2].length()) {
j = 0;
w2++;
}
}
return w1 == word1.length && w2 == word2.length;
}
}
Python
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
i, j, w1, w2 = 0, 0, 0, 0
while w1 < len(word1) and w2 < len(word2):
if word1[w1][i] != word2[w2][j]:
return False
i += 1
if i == len(word1[w1]):
i = 0
w1 += 1
j += 1
if j == len(word2[w2]):
j = 0
w2 += 1
return w1 == len(word1) and w2 == len(word2)
Complexity
- ⏰ Time complexity:
O(n + m)
for comparing characters. - 🧺 Space complexity:
O(1)
since we only use pointers and variables.