Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1662. Check If Two String Arrays are Equivalent - Leetcode Solution

Problem Description

You are given two string arrays, word1 and word2. Your task is to determine if the two arrays represent the same string when all their elements are concatenated in order. In other words, concatenate all strings in word1 to form a single string, do the same for word2, and check if the resulting two strings are identical.

  • Each element in word1 and word2 is a non-empty string consisting of lowercase English letters.
  • You must not reorder or reuse elements; each string is used exactly once, in the order given.
  • Return true if the concatenated strings are the same, and false otherwise.

Thought Process

At first glance, the problem seems simple: just join the arrays into strings and compare them. This is a straightforward approach, but let's consider possible optimizations and edge cases.

  • The brute-force solution is to use the language's built-in string joining functions, which is efficient and clean for this problem.
  • We might consider more manual approaches if, for example, the arrays are huge and memory is a concern. In that case, we could compare the strings character by character as we iterate through both arrays, without building the full concatenated strings in memory.
  • However, for most practical purposes and given the problem's constraints, the direct join-and-compare approach is optimal and easy to implement.

The key insight is that concatenation and comparison are both linear time operations, and we don't need to get fancy unless there's a specific constraint on memory usage.

Solution Approach

Let's break down the solution step by step:

  1. Concatenate Each Array: For both word1 and word2, join all the strings in their given order to form two single strings.
  2. Compare the Results: Check if the two resulting strings are exactly the same.
  3. Return the Result: If they are equal, return true; otherwise, return false.

Why this works: Since the problem only asks for equality after concatenation, and both arrays are traversed once, this approach is both time and space efficient for the problem's constraints.

Alternative (Optimized for Memory): If memory usage is a concern, we can use two pointers to walk through both arrays character by character, comparing as we go, and return false as soon as we find a mismatch. This avoids building the full strings in memory.

Example Walkthrough

Let's consider the following example:

  • word1 = ["ab", "c"]
  • word2 = ["a", "bc"]

Step-by-step process:

  1. Concatenate word1: "ab" + "c" = "abc"
  2. Concatenate word2: "a" + "bc" = "abc"
  3. Compare the two strings: "abc" == "abc"true

Therefore, the function should return true for this input.

Another example:
word1 = ["a", "cb"], word2 = ["ab", "c"]
"a" + "cb" = "acb", "ab" + "c" = "abc"
"acb" != "abc", so return false.

Code Implementation

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        return ''.join(word1) == ''.join(word2)
      
class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        string s1, s2;
        for (auto &w : word1) s1 += w;
        for (auto &w : word2) s2 += w;
        return s1 == s2;
    }
};
      
class Solution {
    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        for (String w : word1) s1.append(w);
        for (String w : word2) s2.append(w);
        return s1.toString().equals(s2.toString());
    }
}
      
var arrayStringsAreEqual = function(word1, word2) {
    return word1.join('') === word2.join('');
};
      

Time and Space Complexity

Brute-force Approach:
- Time Complexity: O(N + M), where N is the total number of characters in word1 and M is the total number in word2. This is because we have to traverse all characters to concatenate and then compare.
- Space Complexity: O(N + M), since concatenating the arrays creates two new strings of length N and M.

Optimized Approach (Character-by-Character):
- Time Complexity: Still O(N + M), as every character must be checked.
- Space Complexity: O(1), since we don't build new strings but compare in place.

For the problem's constraints, the brute-force solution is acceptable and simple to implement.

Summary

The problem asks us to check if two arrays of strings, when concatenated, are equal. The simplest and most effective solution is to join both arrays into strings and compare them. This approach is efficient for both time and space given the problem's scope. For extremely large inputs, a character-by-character comparison can save memory. The solution demonstrates how sometimes the direct approach is the most elegant, leveraging built-in language features for concise and readable code.