Leetcode 1662. Check If Two String Arrays are Equivalent
The problem “1662. Check If Two String Arrays are Equivalent” requires us to determine if two string arrays are equivalent. Two string arrays are considered equivalent if their concatenation results in the same string.
word1
and word2
non-empty?Let’s assume:
word1
and word2
contain only lowercase English letters.public class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String word : word1) {
sb1.append(word);
}
for (String word : word2) {
sb2.append(word);
}
return sb1.toString().equals(sb2.toString());
}
}
StringBuilder
to concatenate all the strings in each array since StringBuilder
is more efficient for string concatenations compared to using the +
operator repeatedly. Using a StringBuilder
helps in minimizing the number of objects created and thus reduces memory overhead.word1
, concatenating it into a StringBuilder
.word2
.StringBuilder
objects to strings and compare them using the equals
method.word1
.word2
.StringBuilder
is ( O(n) + O(m) ).Thus, the overall time complexity is: [ O(n + m) ]
This solution is efficient and straightforward, operating within linear time relative to the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?