We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check If Two String Arrays are Equivalent

Number: 1781

Difficulty: Easy

Paid? No

Companies: Meta, Amazon, Apple


Problem Description

Given two arrays of strings, word1 and word2, determine if the two arrays represent the same string when all the elements in each array are concatenated in order.


Key Insights

  • Concatenating elements in order will produce the final string representation.
  • The comparison can be done efficiently using built-in string operations.
  • Since the total number of characters is limited (at most 10^3), simple concatenation is acceptable.
  • An alternative approach is to use a two-pointer technique to compare character by character without generating full strings.

Space and Time Complexity

Time Complexity: O(n + m), where n and m are the total lengths of word1 and word2. Space Complexity: O(n + m) if using concatenated strings for comparison.


Solution

We approach the problem by concatenating the arrays into a single string each using efficient string join operations in the respective programming languages and then comparing the two resulting strings. This method is simple, effective, and easy to understand. It leverages the built-in functionality of each programming language to handle string concatenation and comparison efficiently.


Code Solutions

# Function to check if two string arrays are equivalent
def arrayStringsAreEqual(word1, word2):
    # Concatenate all elements from word1 and word2 to form the final strings
    str1 = "".join(word1)  # Joining all strings in list word1
    str2 = "".join(word2)  # Joining all strings in list word2
    # Return the comparison result of the two concatenated strings
    return str1 == str2

# Example usage:
print(arrayStringsAreEqual(["ab", "c"], ["a", "bc"]))  # Expected output: True
← Back to All Questions