Word Squares - Problem

Given an array of unique strings words, return all the word squares you can build from words. The same word from words can be used multiple times. You can return the answer in any order.

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).

For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically:

b a l l
a r e a
l e a d
l a d y

Notice that words[0][0] = words[0][0], words[0][1] = words[1][0], words[0][2] = words[2][0], and so on.

Input & Output

Example 1 — Perfect Word Square
$ Input: words = ["area","lead","wall","lady","ball"]
Output: [["ball","area","lead","lady"]]
💡 Note: The word square is: b-a-l-l, a-r-e-a, l-e-a-d, l-a-d-y. Each row equals its corresponding column: ball/ball, area/area, lead/lead, lady/lady.
Example 2 — No Valid Square
$ Input: words = ["abat","baba","atan","atal"]
Output: []
💡 Note: No combination of these words can form a valid word square where each row matches its corresponding column.
Example 3 — Single Character Words
$ Input: words = ["a","b"]
Output: [["a"],["b"]]
💡 Note: Single character words automatically form valid 1x1 word squares.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 4
  • All words[i] have the same length
  • words[i] consists of only lowercase English letters
  • All words[i] are unique

Visualization

Tap to expand
Word Squares: Symmetric Character GridInput Words"ball""area""lead""lady""wall"Valid Word SquareballarealeadladyRow 0 = Column 0: "ball"Row 1 = Column 1: "area"Row 2 = Column 2: "lead"Row 3 = Column 3: "lady"Output: [["ball","area","lead","lady"]]
Understanding the Visualization
1
Input
Array of words of equal length
2
Arrange
Form square where word[i][j] = word[j][i]
3
Validate
Check that each row equals its column
Key Takeaway
🎯 Key Insight: Build squares incrementally using backtracking with prefix-based pruning for efficiency
Asked in
Google 25 Facebook 18 Amazon 12
28.0K Views
Medium Frequency
~35 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