Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether two string arrays are equivalent or not in Python
Suppose we have two string arrays word1 and word2, we need to check whether they represent the same string when their elements are concatenated in order. A string can be represented by an array if concatenating all elements in that array forms the original string.
So, if the input is like word1 = ["ko", "lka", "ta"] and word2 = ["k", "olk", "at", "a"], then the output will be True as both arrays form "kolkata" when concatenated.
Approach
To solve this, we will follow these steps:
Initialize two empty strings s1 and s2
Concatenate all strings in word1 to form s1
Concatenate all strings in word2 to form s2
Compare s1 and s2 for equality
Method 1: Using String Concatenation
The basic approach concatenates strings using a loop ?
def solve(word1, word2):
s1 = ''
s2 = ''
for i in word1:
s1 += i
for i in word2:
s2 += i
return s1 == s2
word1 = ["ko", "lka", "ta"]
word2 = ["k", "olk", "at", "a"]
print(solve(word1, word2))
True
Method 2: Using join() Method
A more efficient approach using Python's built-in join() method ?
def solve(word1, word2):
s1 = ''.join(word1)
s2 = ''.join(word2)
return s1 == s2
word1 = ["ko", "lka", "ta"]
word2 = ["k", "olk", "at", "a"]
print(solve(word1, word2))
True
Method 3: One-Line Solution
The most concise approach using direct comparison ?
def solve(word1, word2):
return ''.join(word1) == ''.join(word2)
word1 = ["ko", "lka", "ta"]
word2 = ["k", "olk", "at", "a"]
print(solve(word1, word2))
True
Example with Different Results
Let's test with arrays that form different strings ?
def solve(word1, word2):
return ''.join(word1) == ''.join(word2)
word1 = ["hello", "world"]
word2 = ["hel", "lo", "wor", "ld"]
word3 = ["hell", "owo", "rld"]
print(f"word1 vs word2: {solve(word1, word2)}")
print(f"word1 vs word3: {solve(word1, word3)}")
print(f"Concatenated word1: {''.join(word1)}")
print(f"Concatenated word3: {''.join(word3)}")
word1 vs word2: True word1 vs word3: False Concatenated word1: helloworld Concatenated word3: helloworld
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| String Concatenation | O(n) | O(n) | Good |
| join() Method | O(n) | O(n) | Better |
| One-Line | O(n) | O(n) | Best |
Conclusion
The join() method provides the most efficient and readable solution for checking string array equivalence. Use the one-line approach for concise code or the basic concatenation method when step-by-step logic is preferred.
