Facebook Pixel

1662. Check If Two String Arrays are Equivalent

Problem Description

You are given two arrays of strings: word1 and word2. Your task is to determine if these two arrays represent the same string when their elements are concatenated together in order.

An array represents a string by concatenating all its elements sequentially. For example, if word1 = ["ab", "c"], it represents the string "abc" (formed by joining "ab" + "c").

You need to return true if both arrays form the exact same string after concatenation, and false otherwise.

Example scenarios:

  • If word1 = ["ab", "c"] and word2 = ["a", "bc"], both represent "abc", so return true
  • If word1 = ["a", "cb"] and word2 = ["ab", "c"], they represent "acb" and "abc" respectively, so return false

The solution approach is straightforward: concatenate all strings in each array using ''.join() and compare if the resulting strings are equal.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that we need to check if two arrays of strings represent the same final string when concatenated. Instead of trying to compare the arrays element by element with complex indexing (which would be error-prone since the arrays might have different lengths and each string might have different lengths), we can simplify the problem.

Think of it this way: if we're asked whether two puzzle pieces, when assembled, create the same picture, the most direct way is to assemble both puzzles and compare the complete pictures. Similarly, rather than trying to compare the arrays piece by piece, we can build the complete strings from both arrays and directly compare them.

The natural approach is to:

  1. Transform the first array into its complete string representation
  2. Transform the second array into its complete string representation
  3. Check if these two strings are identical

This transforms a potentially complex array comparison problem into a simple string equality check. Python's ''.join() method is perfect for this - it concatenates all elements in a list into a single string. So ''.join(word1) == ''.join(word2) elegantly solves the problem in one line.

This approach works because string equality in Python checks character-by-character equality, which is exactly what we need to verify if the two arrays represent the same string.

Solution Approach

The solution uses string concatenation to solve this problem efficiently.

Implementation Steps:

  1. Concatenate the first array: Use Python's ''.join(word1) to combine all strings in the first array into a single string. The join() method takes an iterable (in this case, the list word1) and concatenates all its elements using the string it's called on as a separator. Since we use an empty string '' as the separator, the elements are joined without any characters in between.

  2. Concatenate the second array: Similarly, use ''.join(word2) to combine all strings in the second array into a single string.

  3. Compare the results: Use the equality operator == to check if both concatenated strings are identical. This performs a character-by-character comparison and returns true if they match exactly, false otherwise.

Code Implementation:

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        return ''.join(word1) == ''.join(word2)

Time Complexity: O(n + m) where n is the total number of characters in word1 and m is the total number of characters in word2. We need to traverse all characters once to build each string and once more for comparison.

Space Complexity: O(n + m) as we create two new strings to store the concatenated results.

This approach is both simple and efficient, avoiding the complexity of manually iterating through indices of potentially different-sized arrays and strings.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example to understand how the solution works.

Given:

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

Step 1: Concatenate word1

  • We call ''.join(word1)
  • This takes each element in word1 and joins them with an empty string separator
  • Process: "ab" + "" + "c" = "abc"
  • Result: "abc"

Step 2: Concatenate word2

  • We call ''.join(word2)
  • This takes each element in word2 and joins them with an empty string separator
  • Process: "a" + "" + "bc" = "abc"
  • Result: "abc"

Step 3: Compare the results

  • We check if "abc" == "abc"
  • Since both strings are identical character-by-character, the comparison returns true

Another example where the arrays are NOT equal:

  • word1 = ["a", "cb"]''.join(word1) = "acb"
  • word2 = ["ab", "c"]''.join(word2) = "abc"
  • Compare: "acb" == "abc" returns false because the characters at positions 1 and 2 are different

This demonstrates why the simple concatenation approach works: it transforms the array comparison problem into a straightforward string equality check, handling all the complexity of different array lengths and element sizes automatically.

Solution Implementation

1class Solution:
2    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
3        """
4        Check if two string arrays represent the same string when concatenated.
5      
6        Args:
7            word1: First list of strings to concatenate
8            word2: Second list of strings to concatenate
9          
10        Returns:
11            True if concatenated strings are equal, False otherwise
12        """
13        # Concatenate all strings in word1 into a single string
14        concatenated_word1 = ''.join(word1)
15      
16        # Concatenate all strings in word2 into a single string
17        concatenated_word2 = ''.join(word2)
18      
19        # Compare the two concatenated strings for equality
20        return concatenated_word1 == concatenated_word2
21
1class Solution {
2    /**
3     * Checks if two arrays of strings represent the same string when concatenated.
4     * 
5     * @param word1 First array of strings to be concatenated
6     * @param word2 Second array of strings to be concatenated
7     * @return true if both arrays form the same string when concatenated, false otherwise
8     */
9    public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
10        // Concatenate all strings in word1 array into a single string
11        String concatenatedWord1 = String.join("", word1);
12      
13        // Concatenate all strings in word2 array into a single string
14        String concatenatedWord2 = String.join("", word2);
15      
16        // Compare the two concatenated strings for equality
17        return concatenatedWord1.equals(concatenatedWord2);
18    }
19}
20
1class Solution {
2public:
3    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
4        // Concatenate all strings in word1 into a single string
5        string concatenated_word1 = "";
6        for (const string& str : word1) {
7            concatenated_word1 += str;
8        }
9      
10        // Concatenate all strings in word2 into a single string
11        string concatenated_word2 = "";
12        for (const string& str : word2) {
13            concatenated_word2 += str;
14        }
15      
16        // Compare the two concatenated strings for equality
17        return concatenated_word1 == concatenated_word2;
18    }
19};
20
1/**
2 * Checks if two arrays of strings represent the same string when concatenated
3 * @param word1 - First array of strings to concatenate and compare
4 * @param word2 - Second array of strings to concatenate and compare
5 * @returns true if both arrays form the same string when concatenated, false otherwise
6 */
7function arrayStringsAreEqual(word1: string[], word2: string[]): boolean {
8    // Concatenate all strings in word1 and word2, then compare the results
9    return word1.join('') === word2.join('');
10}
11

Time and Space Complexity

The time complexity is O(m), where m is the total length of all strings in both arrays combined. This is because:

  • ''.join(word1) iterates through all characters in word1 to create a new string, taking O(m1) time where m1 is the total length of strings in word1
  • ''.join(word2) iterates through all characters in word2 to create a new string, taking O(m2) time where m2 is the total length of strings in word2
  • The comparison == between two strings takes O(min(m1, m2)) time in the worst case
  • Overall: O(m1 + m2 + min(m1, m2)) = O(m1 + m2) = O(m)

The space complexity is O(m), where m is the total length of all strings in both arrays combined. This is because:

  • ''.join(word1) creates a new string containing all characters from word1, requiring O(m1) space
  • ''.join(word2) creates a new string containing all characters from word2, requiring O(m2) space
  • Total space used: O(m1 + m2) = O(m)

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Memory Inefficiency with Large Strings

The current solution creates two complete concatenated strings in memory before comparing them. For very large arrays with long strings, this can consume significant memory unnecessarily.

Why it's a problem: If the total character count is in millions, creating full strings just to compare them wastes memory when we could determine inequality early.

Better approach: Use generators or iterators to compare character-by-character without building complete strings:

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        def generate_chars(word_array):
            for word in word_array:
                for char in word:
                    yield char
      
        # Compare characters one by one using iterators
        return all(c1 == c2 for c1, c2 in itertools.zip_longest(
            generate_chars(word1), 
            generate_chars(word2), 
            fillvalue=None
        ))

2. Not Handling Edge Cases Explicitly

While Python's join() handles empty lists and empty strings gracefully, not considering these cases explicitly can lead to confusion:

  • Empty arrays: word1 = [] or word2 = []
  • Arrays with empty strings: word1 = ["", "a", ""]
  • Single empty string: word1 = [""]

Solution: Although the current code handles these correctly, documenting expected behavior or adding explicit checks can improve code clarity:

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        # Handle empty arrays explicitly for clarity
        if not word1 and not word2:
            return True
        if not word1 or not word2:
            return False
          
        return ''.join(word1) == ''.join(word2)

3. Type Assumptions Without Validation

The code assumes all elements in the arrays are valid strings. In production code, invalid types could cause runtime errors.

Solution: Add type validation if needed:

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        # Validate that all elements are strings
        if not all(isinstance(s, str) for s in word1 + word2):
            raise TypeError("All array elements must be strings")
          
        return ''.join(word1) == ''.join(word2)

4. Early Termination Optimization Missed

The current solution always builds both complete strings even when we could determine inequality earlier by checking total lengths first.

Optimization:

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        # Quick length check before concatenation
        total_len1 = sum(len(s) for s in word1)
        total_len2 = sum(len(s) for s in word2)
      
        if total_len1 != total_len2:
            return False
          
        return ''.join(word1) == ''.join(word2)

This avoids string concatenation when lengths differ, though for small inputs the overhead might not be worth it.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which of the tree traversal order can be used to obtain elements in a binary search tree in sorted order?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More