⚡Flashcard Drill➔
NeetCode #191LC-1662EasyTwo Pointers
← Back to All Problems

#191 · #1662 · Check If Two String Arrays are Equivalent(检查两个字符串数组是否相等)

📌 Problem Statement & Constraints

Given two string arrays word1 and word2, return whether the two arrays represent the same string when concatenated. Constraints: 1 <= word1.length, word2.length <= 10^3, 1 <= word1[i].length, word2[i].length <= 10^3.

💡 Core Algorithmic Approaches

  1. The simplest approach concatenates each array and compares the results, which is O(total characters) time and space.
  2. A follow-up asks for O(1) extra space: use four pointers -- an array index and a character index for each side -- and compare characters one at a time, advancing to the next word when a word is exhausted.
  3. Both versions are O(total characters) time; only the space differs.
  4. The pointer version is a good exercise in multi-pointer bookkeeping.

💻 Benchmark Python3 Implementation

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        return "".join(word1) == "".join(word2)


# O(1)-space variant: four pointers, comparing character by character
class Solution2:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        i = j = 0                      # word indices
        p = q = 0                      # character indices within words
        while i < len(word1) and j < len(word2):
            if word1[i][p] != word2[j][q]:
                return False
            p += 1
            q += 1
            if p == len(word1[i]):     # word exhausted -> advance
                i += 1
                p = 0
            if q == len(word2[j]):
                j += 1
                q = 0
        # equal only if both sides are fully consumed
        return i == len(word1) and j == len(word2)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(total characters): each character is compared once in both variants.
💾 Space Complexity
O(total characters) for the join; O(1) for the pointer variant.

⚠️ Interview Pitfalls & Follow-ups

  • Using == on the arrays themselves: ["ab", "c"] and ["a", "bc"] are different arrays but the same string.
  • Comparing the concatenations without accounting for word boundaries: joining handles this correctly, and the pointer variant advances the word index at the boundary.
  • Forgetting the final exhaustion check in the pointer variant: one side may finish earlier, in which case the strings differ in length.
  • Assuming word lengths are equal: they need not be, which is exactly what the pointer bookkeeping handles.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

检查两个字符串数组是否相等

给你两个字符串数组 word1 和 word2。如果两个数组表示的字符串相同,返回 true;否则,返回 false。数组表示的字符串是由数组中的所有元素 按顺序 连接形成的字符串。约束:1 ≤ word1.length, word2.length ≤ 10^3;1 ≤ word1[i].length, word2[i].length ≤ 10^3;两个数组均由小写英文字母组成。

核心要点

  • 直接拼接比较(标准解) :把两个数组分别拼接成字符串,比较是否相等。
  • 复杂度 :拼接是 O(总长度),比较也是 O(总长度)。
  • 进阶 · O(1) 空间的双指针 :分别用 (i, j) 指向两个数组的「当前单词」与「单词内位置」,逐字符比较,避免创建完整的拼接字符串。
  • 何时需要双指针 :当字符串极长(无法一次性拼接)时,流式比较是必要的。

常见陷阱

  • 比较数组长度而不比较内容 : len(word1) == len(word2) 与字符串相等完全无关。
  • 拼接时漏掉顺序 :必须按数组顺序拼接,不能排序。
  • 双指针版本忘记在单词末尾重置内层下标 : p 与 q 在换单词时必须归零。

参考实现

class Solution:
    def arrayStringsAreEqual(self, word1: list[str], word2: list[str]) -> bool:
        return ''.join(word1) == ''.join(word2)

# O(1) 空间的双指针版本:
# i = j = 0          # 数组下标
# p = q = 0          # 单词内字符下标
# while i < len(word1) and j < len(word2):
#     if word1[i][p] != word2[j][q]:
#         return False
#     p += 1; q += 1
#     if p == len(word1[i]):
#         i += 1; p = 0
#     if q == len(word2[j]):
#         j += 1; q = 0
# return i == len(word1) and j == len(word2)