Word Squares — LeetCode 425 Python Solution

HardLeetCode PremiumTrieArrayStringBacktracking
Problem
#425
Pattern
Trie
Reading time
8 min

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

Example

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

Python solution

Python
class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.v = []

    def insert(self, w, i):
        node = self
        for c in w:
            idx = ord(c) - ord('a')
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
            node.v.append(i)

    def search(self, w):
        node = self
        for c in w:
            idx = ord(c) - ord('a')
            if node.children[idx] is None:
                return []
            node = node.children[idx]
        return node.v


class Solution:
    def wordSquares(self, words: List[str]) -> List[List[str]]:
        def dfs(t):
            if len(t) == len(words[0]):
                ans.append(t[:])
                return
            idx = len(t)
            pref = [v[idx] for v in t]
            indexes = trie.search(''.join(pref))
            for i in indexes:
                t.append(words[i])
                dfs(t)
                t.pop()

        trie = Trie()
        ans = []
        for i, w in enumerate(words):
            trie.insert(w, i)
        for w in words:
            dfs([w])
        return ans

Complexity

MeasureComplexity
TimeExponential (worst case)
SpaceO(depth) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 425. Word Squares is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 425. Word Squares?
LeetCode 425. Word Squares is rated Hard on LeetCode.
What topics does LeetCode 425. Word Squares cover?
LeetCode 425. Word Squares is tagged Trie, Array, String and Backtracking on LeetCode.
Is LeetCode 425. Word Squares a premium problem?
Yes. LeetCode 425. Word Squares is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview