> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Word Squares Python Solution with Tests

> Tested Python solution for LeetCode 425 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 425, [Hard](/catalog/hard). Topics: [Trie](/catalog/topics/trie), [Array](/catalog/topics/array), [String](/catalog/topics/string), [Backtracking](/catalog/topics/backtracking). [View on LeetCode](https://leetcode.com/problems/word-squares/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 425   # by problem number
lcpy gen -s word_squares   # by problem name
```

## Problem

Given an array of **unique** strings `words`, return all the [word squares](https://en.wikipedia.org/wiki/Word_square) 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.

### Examples

```
Input: words = ["area","lead","wall","lady","ball"]
Output: [["ball","area","lead","lady"],["wall","area","lead","lady"]]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
```

```
Input: words = ["abat","baba","atan","atal"]
Output: [["baba","abat","baba","atal"],["baba","abat","baba","atan"]]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
```

### 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**.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/word_squares/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/word_squares/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(N * 26^L) where N = len(words), L = word length
    # Space: O(N * L) for the prefix map
    def word_squares(self, words: list[str]) -> list[list[str]]:
        n = len(words[0])
        prefixes: dict[str, list[str]] = {}
        for word in words:
            for i in range(n + 1):
                prefixes.setdefault(word[:i], []).append(word)

        results: list[list[str]] = []
        square: list[str] = []

        def backtrack() -> None:
            if len(square) == n:
                results.append(square[:])
                return
            prefix = "".join(word[len(square)] for word in square)
            for word in prefixes.get(prefix, []):
                square.append(word)
                backtrack()
                square.pop()

        backtrack()
        return results
```

## Complexity

| Time | Space |
| - | - |
| O(N \* 26^L) where N = len(words), L = word length | O(N \* L) for the prefix map |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.