Check If Two String Arrays Are Equivalent — Solution
Check If Two String Arrays Are Equivalent solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Check If Two String Arrays Are Equivalent is an easy coding problem on arrays and strings, asked in Amazon and Microsoft interviews.
- Difficulty: Easy
- Topics: Arrays, Strings
- Asked at: Amazon, Microsoft
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given two string arrays word1 and word2, return true if the two arrays represent the same string.
An array represents the string formed by concatenating its elements in order.
Example 1
Input: word1 = ["ab","c"], word2 = ["a","bc"]
Output: true
Explanation: Both spell "abc".
Example 2
Input: word1 = ["a","cb"], word2 = ["ab","c"]
Output: false
Example 3
Input: word1 = ["abc","d","defg"], word2 = ["abcddefg"]
Output: true
Constraints
1 <= word1.length, word2.length <= 101 <= word1[i].length, word2[i].length <= 8All strings consist of lowercase English letters.
Hints for Check If Two String Arrays Are Equivalent
Hint 1
Joining both arrays and comparing the results is the direct answer.
Hint 2
To avoid building the strings, walk both arrays with a pair of (array index, character index) cursors and compare character by character.
How to solve Check If Two String Arrays Are Equivalent
Concatenate both arrays and compare the strings.
Approach
- Join
word1andword2into strings. - Return whether they are equal.
Why it works
An array represents its concatenation by definition, so equality of the joined strings is the required test.
Complexity
- Time —
O(total length) - Space —
O(total length)
Pitfalls
- Two
(array index, char index)cursors compare without allocating, if memory matters.
Reference solution
Python
def arrayStringsAreEqual(word1, word2) -> bool:
return "".join(word1) == "".join(word2)Java
public static boolean arrayStringsAreEqual(String[] word1, String[] word2) {
return String.join("", word1).equals(String.join("", word2));
}C++
bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
string a = "";
for (string& w : word1) a += w;
string b = "";
for (string& w : word2) b += w;
return a == b;
}JavaScript
var arrayStringsAreEqual = function(word1, word2) {
return word1.join("") === word2.join("");
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.