A "Word Square" is a sequence of words such that the k-th row and k-th column are the same string. For example, if the first word is AREA, the first column must also be A, R, E, A. Given a list of words of the same length, you need to find all possible word squares that can be formed using those words.
Google loves this problem because it’s a pure test of Backtracking and Prefix Search efficiency. It requires you to realize that choosing the first i words in the square completely determines the required prefix for the (i+1)-th word. This observation is the key to solving the problem efficiently.
The pattern is Backtracking with a Trie.
i-th word, look at the first i characters of the i-th column (which are already determined by the first i-1 words).Words: ["ball", "area", "lead", "lady"].
ball.a (2nd char of ball). Option: area.le (3rd chars of ball and area). Option: lead.lady (4th chars of ball, area, lead). Option: lady.
Square:b a l l
a r e a
l e a d
l a d y
(Check: Row 3 is lead, Col 3 is l, e, a, d. Correct!)
In backtracking problems where you need to "find all words starting with X," a Trie is almost always the right answer. Practice the variant where you store word indices at each Trie node for faster retrieval.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Word Search II | Hard | Solve | |
| Longest Common Suffix Queries | Hard | Solve | |
| Words Within Two Edits of Dictionary | Medium | Solve | |
| Minimum Unique Word Abbreviation | Hard | Solve | |
| Verbal Arithmetic Puzzle | Hard | Solve |