#1662
Check If Two String Arrays are Equivalent
EasyArrayStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of creating two large strings, we can compare the elements of both arrays directly. This avoids unnecessary memory usage and speeds up the process.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, i and j, to 0.
- 2Step 2: Initialize two variables, index1 and index2, to 0 to track the current character position in each string.
- 3Step 3: While both pointers are within their respective array bounds, compare characters at index1 of word1 and index2 of word2.
- 4Step 4: If characters match, move to the next character in both strings. If they don't match, return false.
- 5Step 5: If we finish comparing all characters and both pointers have reached the end of their respective arrays, return true.
solution.py14 lines
1def arrayStringsAreEqual(word1, word2):
2 i, j, index1, index2 = 0, 0, 0, 0
3 while i < len(word1) and j < len(word2):
4 if word1[i][index1] != word2[j][index2]:
5 return False
6 index1 += 1
7 if index1 == len(word1[i]):
8 i += 1
9 index1 = 0
10 index2 += 1
11 if index2 == len(word2[j]):
12 j += 1
13 index2 = 0
14 return i == len(word1) and j == len(word2)ℹ
Complexity note: The time complexity is O(n) because we traverse through each character of both arrays only once. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Concatenating strings can be inefficient; direct comparison is often better.
- 2Understanding how to traverse and compare elements in arrays is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.