Check If Two String Arrays are Equivalent - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
Output: true
💡 Note: word1 represents "ab" + "c" = "abc", word2 represents "a" + "bc" = "abc". Both form the same string "abc".
Example 2 — Different Lengths
$ Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
Output: false
💡 Note: word1 represents "a" + "cb" = "acb", word2 represents "ab" + "c" = "abc". The strings "acb" and "abc" are different.
Example 3 — Single Characters
$ Input: word1 = ["abc"], word2 = ["a", "b", "c"]
Output: true
💡 Note: word1 represents "abc", word2 represents "a" + "b" + "c" = "abc". Both form the same 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.

Visualization

Tap to expand
String Arrays Equivalence Check INPUT word1: "ab" "c" word2: "a" "bc" Concatenated: "abc" <-- word1 "abc" <-- word2 Both form same string after concatenation ALGORITHM STEPS 1 Initialize Pointers i1, w1 = 0 (word1 index) i2, w2 = 0 (word2 index) 2 Compare Char by Char Compare word1[w1][i1] with word2[w2][i2] 3 Advance Pointers Move to next char in string or next string 4 Check Completion Both arrays exhausted at same time = true 'a'=='a' 'b'=='b' 'c'=='c' All characters match! FINAL RESULT Comparison Result: true Why true? word1 concatenates to: "ab" + "c" = "abc" word2 concatenates to: "a" + "bc" = "abc" Output: true Arrays are equivalent! Key Insight: Use two-pointer technique with O(1) space: traverse both arrays simultaneously, comparing characters one by one. When reaching end of a string, move to next string in array. Time: O(n) where n = total characters. No string concatenation needed! TutorialsPoint - Check If Two String Arrays are Equivalent | Optimal Solution
Asked in
Amazon 15 Google 12 Facebook 8
156.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen