Check If Two String Arrays are Equivalent | LeetCode 1662

In this blog, we will solve LeetCode Coding Problem “Check If Two String Arrays are Equivalent”. We will solve this coding problem by iterating over both array and creating two string from them.

Problem Statement

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.

Constraints

  • 1 <= word1.length, word2.length <= 103
  • 1 <= word1[i].length, word2[i].length <= 103
  • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
  • word1[i] and word2[i] consist of lowercase letters.

Example

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.

Solution

We will solve this coding problem by iterating through word1 and word2 array and creating two arrays from them str1 and str2. Now we can compare str1 and str2 to get desired output.

C++ implementation of above solution is as follows

C++
class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        string str1 = "";
        string str2 = "";

        for(int i=0; i<word1.size(); i++) {
            str1 += word1[i];
        }

        for(int i=0; i<word2.size(); i++) {
            str2 += word2[i];
        }

        return str1 == str2;
    }
};

Time Complexity

O(m + n) where m = number of characters in word1 and n = number of characters in word2.

Space Complexity

O(m + n) where m = number of characters in word1 and n = number of characters in word2.

Thanks for reading and have a nice day.