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 - Optimal Solution INPUT words array: "area" "lead" "wall" "lady" "ball" Word Square Property: Row k = Column k b a l l a r e a l e a d l a d y ALGORITHM STEPS 1 Build Prefix Trie Insert all words for fast prefix lookup 2 Backtrack Search Try each word as first row, build square row by row 3 Get Prefix Constraint For row k, prefix = column k chars from rows 0 to k-1 4 Validate and Collect When 4 rows complete, add valid square to result Prefix Trie Structure: * a l b r e a a FINAL RESULT Valid Word Square Found: b a l l a r e a l e a d l a d y Output: [["ball","area","lead","lady"]] 1 valid word square Verification: Row 0 = Col 0 = "ball" OK All rows = columns OK Key Insight: Use a Trie for O(1) prefix lookups. For row k, the required prefix is formed by taking the k-th character from each word in rows 0 to k-1. Backtracking with Trie pruning eliminates invalid paths early, making the solution efficient: O(N * 26^L) where N=words count, L=word length. TutorialsPoint - Word Squares | Trie + Backtracking Approach
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