⚡Flashcard Drill➔
NeetCode #9LC-422EasyArrays & HashingNC Algo100
← Back to All Problems

#9 · #422 · Valid Word Square(有效的单词方阵)

📌 Problem Statement & Constraints

Given an array of strings words, return true if it forms a valid word square: for every valid index pair (i, j), words[i][j] == words[j][i]. Constraints: 1 <= words.length <= 500, 1 <= words[i].length <= 500; all strings consist of lowercase English letters.

💡 Core Algorithmic Approaches

  1. A word square is simply the transpose condition: the matrix must equal its own transpose.
  2. Iterate i over the rows and j over the characters of words[i].
  3. Two failure modes must be checked: j may exceed the number of rows, and i may exceed the length of words[j]. Either means the shape is not square-symmetric.
  4. If words[j] is long enough, compare the characters. Any mismatch fails immediately.

💻 Benchmark Python3 Implementation

class Solution:
    def validWordSquare(self, words: List[str]) -> bool:
        n = len(words)
        for i in range(n):
            for j in range(len(words[i])):
                # need words[j][i] to exist and match words[i][j]
                if j >= n or i >= len(words[j]) or words[i][j] != words[j][i]:
                    return False
        return True

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(total characters): each character of the input is inspected at most once.
💾 Space Complexity
O(1) extra space -- only loop indices.

⚠️ Interview Pitfalls & Follow-ups

  • Only checking words[i][j] != words[j][i]: this raises IndexError when the shape is ragged, e.g. ["abc", "b"] -- words[1][2] does not exist.
  • Assuming the array is a perfect square: it need not be; the length checks are the whole point of the problem.
  • Building the transpose explicitly: it works and is clearer, but allocates O(total characters) for no reason.
⚡
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 Arrays & Hashing Problems

中文速览与面试要点

有效的单词方阵

给你一个字符串数组 words,如果它能构成一个有效的单词方阵则返回 true,否则返回 false。有效的单词方阵要求:对于所有合法的 i、j,满足 words[i][j] == words[j][i] 。注意 words[i] 的长度可能互不相同,此时「越界」也必须是 对称越界 (若 words[i] 没有第 j 个字符,则 words[j] 也不能有第 i 个字符)。约束:1 ≤ words.length ≤ 500;1 ≤ words[i].length ≤ 500;words[i] 仅含小写英文字母。

核心要点

  • 直接照定义做(标准解) :外层遍历行下标 i,内层遍历列下标 j(范围为 0..len(words[i])-1 )。对每个 (i, j) 检查转置位置的字符是否相同。
  • 对称越界的处理(本题唯一考点) :检查时必须同时判断 j &gt;= len(words) 或 i &gt;= len(words[j]) 。只要转置位置越界,就说明两个词长度不对称,直接返回 False。
  • 为什么不能只比较 len(words[i]) == len(words[j]) :长度相等只是必要条件之一,真正要求的是 每一个位置 的字符都对称相等。
  • 等价视角 :把 words 看作一个矩阵,本题就是判断该矩阵是否等于它的转置(即是否为对称矩阵)。

常见陷阱

  • 漏掉越界判断 :只写 words[i][j] != words[j][i] 会在行长不等时抛 IndexError。本题的难点全在这个边界上。
  • 反向漏检 :只检查 words[i][j] 存在的情况,而忽略「words[i] 比 words[j] 长」的反向不对称。上面的写法通过 j &gt;= n or i &gt;= len(words[j]) 同时覆盖了两个方向。
  • 误以为行长必须全部相等 :有效的单词方阵 允许 行长不等,只要越界是对称的(例如 ["abc","b"] 不合法,但 ["a",""] 需要仔细推敲边界)。

参考实现

class Solution:
    def validWordSquare(self, words: list[str]) -> bool:
        n = len(words)
        for i in range(n):
            for j in range(len(words[i])):
                # 转置位置越界,或字符不对称 -> 不是单词方阵
                if j >= n or i >= len(words[j]) or words[i][j] != words[j][i]:
                    return False
        return True