Leetcode #422: Valid Word Square
In this guide, we solve Leetcode #422 Valid Word Square in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an array of strings words, return true if it forms a valid word square. A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Array, Matrix
Intuition
Grid problems are easiest when you define clear row/column boundaries.
A consistent traversal order prevents off-by-one errors.
Approach
Iterate by rows, columns, or layers depending on the requirement.
Keep bounds updated as the traversal progresses.
Steps:
- Define bounds or directions.
- Visit cells in order.
- Update result and move bounds.
Example
Input: words = ["abcd","bnrt","crmy","dtye"]
Output: true
Explanation:
The 1st row and 1st column both read "abcd".
The 2nd row and 2nd column both read "bnrt".
The 3rd row and 3rd column both read "crmy".
The 4th row and 4th column both read "dtye".
Therefore, it is a valid word square.
Python Solution
class Solution:
def validWordSquare(self, words: List[str]) -> bool:
m = len(words)
for i, w in enumerate(words):
for j, c in enumerate(w):
if j >= m or i >= len(words[j]) or c != words[j][i]:
return False
return True
Complexity
The time complexity is , where is the length of words. The space complexity is $O(1)`.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.