Valid Word Square Problem
Description
LeetCode Problem 422.
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 k^th row and column read the same string, where 0 <= k < max(numRows, numColumns).
Example 1:

Input: words = ["abcd","bnrt","crmy","dtye"]
Output: true
Explanation:
The 1^st row and 1^st column both read "abcd".
The 2^nd row and 2^nd column both read "bnrt".
The 3^rd row and 3^rd column both read "crmy".
The 4^th row and 4^th column both read "dtye".
Therefore, it is a valid word square.
Example 2:

Input: words = ["abcd","bnrt","crm","dt"]
Output: true
Explanation:
The 1^st row and 1^st column both read "abcd".
The 2^nd row and 2^nd column both read "bnrt".
The 3^rd row and 3^rd column both read "crm".
The 4^th row and 4^th column both read "dt".
Therefore, it is a valid word square.
Example 3:

Input: words = ["ball","area","read","lady"]
Output: false
Explanation:
The 3^rd row reads "read" while the 3^rd column reads "lead".
Therefore, it is NOT a valid word square.
Constraints:
1 <= words.length <= 5001 <= words[i].length <= 500words[i]consists of only lowercase English letters.
Solution
Approach: Compare Each Cell with Its Mirror
Row k and column k read the same string for every k exactly when the grid is symmetric about its main diagonal: every letter words[i][j] has a mirror words[j][i], and the two are equal.
So go through every letter words[i][j] and check its mirror:
j < len(words): there must be a rowjat all;i < len(words[j]): rowjmust be long enough to have a columni;words[j][i] == words[i][j].
If any check fails, return false.
The rows can have different lengths (Example 2), so do not build a transposed grid or assume an n x n square. Checking only the letters that exist is enough, because the check runs in both directions. If column i has a letter in row j that row i lacks, that letter is words[j][i], and its own check finds that words[i] is too short. Example 3 fails at words[2][0] = 'r', whose mirror words[0][2] is 'l'.
Complexity: O(total number of letters) time, at most O(n2) for n rows of length up to n. O(1) extra space.
class Solution:
def validWordSquare(self, words: List[str]) -> bool:
n = len(words)
for i, word in enumerate(words):
for j, c in enumerate(word):
# Row i, column j must equal row j, column i, and that cell must exist.
if j >= n or i >= len(words[j]) or words[j][i] != c:
return False
return True