AlgoInsight

DSA problem

Word Squares

HardTriesPattern: Triestop600GoogleAmazonMicrosoftBloombergApple

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, for all 0 <= k < max(numRows, numCols). For example, the sequence ["ball","area","lead","lady"] forms a word square because each row reads the same as the corresponding column.

The brute-force approach picks any word for the first row, then for each subsequent row scans the entire dictionary looking for words that satisfy the symmetric constraint. With N words of length L that costs O(N^L) in the worst case — completely impractical.

The optimal approach uses a Trie indexed by every prefix of every word: each Trie node stores the list of words that pass through it. To choose the k-th row of a partial square, we compute the required prefix (the characters in column k from already-placed rows) and ask the Trie in O(L) for every word that begins with it. Backtracking then becomes very tight: only viable candidates are tried at each level, slashing the search space dramatically.

Examples

Example 1
Input: words = ["area","lead","wall","lady","ball"]
Output: [["ball","area","lead","lady"],["wall","area","lead","lady"]]
Explanation: Both ["ball","area","lead","lady"] and ["wall","area","lead","lady"] satisfy the word-square symmetry: row k and column k read the same string for every k.
Example 2
Input: words = ["abat","baba","atan","atal"]
Output: [["baba","abat","baba","atal"],["baba","abat","baba","atan"]]
Explanation: Both sequences form a 4x4 square where reading any row gives the same string as reading the column with the same index.
Example 3
Input: words = ["a"]
Output: [["a"]]
Explanation: A single 1-character word trivially forms a 1x1 word square consisting of just that word.

Constraints

4 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

triebacktrackingstringmatrix

Browse all DSA problems