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
- A word square is simply the transpose condition: the matrix must equal its own transpose.
- Iterate
iover the rows andjover the characters ofwords[i]. - Two failure modes must be checked:
jmay exceed the number of rows, andimay exceed the length ofwords[j]. Either means the shape is not square-symmetric. - 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 raisesIndexErrorwhen 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.