Valid Word Square
Problem
Given a sequence of words, return whether they form a valid word square (the kth row reads the same as the kth column).
words = ["abcd","bnrt","crmy","dtye"]truedef valid_word_square(words):
n = len(words)
for r, row in enumerate(words):
for c, ch in enumerate(row):
if c >= n or r >= len(words[c]) or words[c][r] != ch:
return False
# also ensure row length doesn't claim more than column allows
for c in range(len(row), len(words[0])):
if c < n and r < len(words[c]):
return False
return True
function validWordSquare(words) {
const n = words.length;
for (let r = 0; r < n; r++) {
for (let c = 0; c < words[r].length; c++) {
if (c >= n || r >= words[c].length || words[c][r] !== words[r][c]) return false;
}
}
for (let c = 0; c < n; c++) {
for (let r = 0; r < words[c].length; r++) {
if (r >= n || c >= words[r].length || words[c][r] !== words[r][c]) return false;
}
}
return true;
}
class Solution {
public boolean validWordSquare(List words) {
int n = words.size();
for (int r = 0; r < n; r++) {
String row = words.get(r);
for (int c = 0; c < row.length(); c++) {
if (c >= n || r >= words.get(c).length() || words.get(c).charAt(r) != row.charAt(c)) return false;
}
}
return true;
}
}
bool validWordSquare(vector& words) {
int n = words.size();
for (int r = 0; r < n; r++) {
for (int c = 0; c < (int)words[r].size(); c++) {
if (c >= n || r >= (int)words[c].size() || words[c][r] != words[r][c]) return false;
}
}
return true;
}
Explanation
A word square reads the same across rows and down columns: row k must equal column k. The check boils down to one symmetry rule: the letter at (r, c) must match the letter at (c, r) for every cell that exists.
The active solution walks every character of every word. For row r, position c, it compares words[r][c] with words[c][r]. If they differ, the square is invalid.
It also guards the edges where rows have different lengths. Before comparing, it checks c >= n (no row c exists) or r >= words[c].length (row c is too short to have a position r). Either situation breaks the mirror, so it returns false.
Example: ["abcd","bnrt","crmy","dtye"]. Cell (0,1) is b and cell (1,0) is also b — they match. Every mirrored pair lines up, so the answer is true.
Because it confirms each pair matches in both directions and that no position is missing on one side, passing the whole scan means the grid is a genuine word square.