LeetCode — Check If Two String Arrays are Equivalent

Siddhant Jain
2 min readJan 8, 2021

--

Problem Link: https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/

Strings
Photo by Dominik Scythe on Unsplash

Problem Description: 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.

Example 1:
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.
Example 2:
Input:
word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false

Approach Used: Arrays traversal, String comparison

Explanation: This a very basic question. It is a beginner-friendly question which requires not much logic. We simply need to combine all the substrings in the array into one combines string for both the arrays. The order of combining should not change. After we get both the combined substring, we’ll simply compare them and return true is all the characters match, otherwise false.

Code: (Java)

public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
//intializing 2 empty strings
String combinedString1 = "";
String combinedString2 = "";

//getting combined string from first array
for(int i=0; i<word1.length; i++)
combinedString1+=word1[i];

//getting combined string from second array
for(int i=0; i<word2.length; i++)
combinedString2+=word2[i];

//checking if they match or not and returning appropriate output
return combinedString1.equals(combinedString2);
}
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
//intializing 2 empty strings
String combinedString1 = "";
String combinedString2 = "";

//getting combined string from first array
for(int i=0; i<word1.length; i++)
combinedString1+=word1[i];

//getting combined string from second array
for(int i=0; i<word2.length; i++)
combinedString2+=word2[i];

//checking if they match or not and returning appropriate output
return combinedString1.equals(combinedString2);
}

Complexity:
Space Complexity: O(m+n) where m and n will be total characters present in array1 and array2 respectively.
Time Complexity: O(a+b) where a and b are the length of both arrays.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response