Valid Word Square - Problem

Imagine you have a collection of words arranged in a grid, like a crossword puzzle. Your task is to determine if this grid forms a valid word square - a special arrangement where each row reads exactly the same as its corresponding column.

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 k-th column read the same string, where 0 ≤ k < max(numRows, numColumns).

Example: If words = ["abcd", "bnrt", "crmy", "dtye"], then:
• Row 0: "abcd" vs Column 0: "abcd" ✓
• Row 1: "bnrt" vs Column 1: "bnrt" ✓
• Row 2: "crmy" vs Column 2: "crmy" ✓
• Row 3: "dtye" vs Column 3: "dtye" ✓

This is a valid word square because each row matches its corresponding column perfectly!

Input & Output

example_1.py — Valid Word Square
$ Input: ["abcd", "bnrt", "crmy", "dtye"]
Output: true
💡 Note: This forms a perfect word square: Row 0 'abcd' matches Column 0 'abcd', Row 1 'bnrt' matches Column 1 'bnrt', and so on. Each row-column pair is identical.
example_2.py — Invalid Word Square
$ Input: ["abcd", "bnrt", "crm", "dt"]
Output: false
💡 Note: Row 2 is 'crm' but Column 2 is 'crmd' (taking 3rd character from each row). The lengths don't match, making this invalid.
example_3.py — Single Character Square
$ Input: ["ball", "area", "lead", "lady"]
Output: false
💡 Note: Row 0 'ball' vs Column 0 'ball' ✓, but Row 1 'area' vs Column 1 'aree' ✗. The second column spells 'aree' not 'area'.

Constraints

  • 1 ≤ words.length ≤ 500
  • 1 ≤ words[i].length ≤ 500
  • words[i] consists of only lowercase English letters
  • Matrix dimensions may be uneven - number of rows may differ from maximum column length

Visualization

Tap to expand
Word Square: Mirror Diagonal ValidationballareaMirror LineCheck: b = b ✓
Understanding the Visualization
1
Check Matrix Bounds
Ensure we can access both words[i][j] and words[j][i] safely
2
Compare Mirror Positions
For each valid (i,j), verify words[i][j] equals words[j][i]
3
Handle Edge Cases
Account for missing characters when row lengths vary
4
Return Validation Result
True if all mirror positions match, false otherwise
Key Takeaway
🎯 Key Insight: A word square is valid when it's symmetric across the main diagonal - each character at position (i,j) must equal the character at position (j,i).
Asked in
Google 45 Amazon 38 Microsoft 25 Meta 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen