Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #425: Word Squares

In this guide, we solve Leetcode #425 Word Squares in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Trie, Array, String, Backtracking

Intuition

We must explore combinations of choices, but many branches can be pruned early.

Backtracking enumerates valid candidates while keeping the search space under control.

Approach

Use DFS to build candidates step by step, and backtrack when constraints are violated.

Pruning keeps the exploration practical for typical constraints.

Steps:

  • Define the decision tree.
  • DFS through choices and backtrack.
  • Prune invalid paths early.

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

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

The time complexity is Exponential (worst case). The space complexity is O(depth).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy