Word Squares Problem
Description
LeetCode Problem 425.
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, 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.
Example 1:
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).
Example 2:
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 <= 10001 <= 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
Approach: Backtracking with a Prefix Map
Build the square one row at a time. The rows already placed decide a lot about the next one. In a word square, row k equals column k, and the first k letters of column k are already known: they are the k-th letters of rows 0 .. k-1. So row k must start with that prefix.
With ["ball", "area"] placed, row 2 must start with "le" (the third letters of ball and area), and row 3 with "lad" once "lead" is placed.
This turns the search into "find all words with a given prefix", over and over. Precompute it: map every prefix of every word (including the empty prefix, which matches all words) to the list of words that start with it. A trie does the same job; with words of at most 4 letters a hash map of prefixes is just as fast and simpler.
The backtracking:
- If
Lrows are placed (Lis the word length,nin the code), the square is complete: record a copy. - Otherwise build the prefix for row
kfrom the rows so far, and try every word inbyPrefix[prefix]as rowk, recursing after each one.
Checking the prefix is all that is needed. When a word is chosen for row k, its first k letters agree with the columns above, and its remaining letters set the start of the later columns, which the later rows must then match. A word may be used more than once, as baba is in Example 2, so nothing is marked as used.
Complexity: O(m · L) time to build the map for m words of length L. The search takes time proportional to the number of partial squares it explores, at most O(mL · L) in theory, and much less in practice because each prefix allows few words. O(m · L2) space for the map, plus the output.
import collections
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
n = len(words[0])
# prefix -> every word that starts with it
by_prefix = collections.defaultdict(list)
for word in words:
for k in range(n):
by_prefix[word[:k]].append(word)
squares = []
rows = []
def build() -> None:
k = len(rows)
if k == n:
squares.append(rows[:])
return
# Row k must start with column k so far: the k-th letter of every row above.
prefix = "".join(row[k] for row in rows)
for word in by_prefix.get(prefix, []):
rows.append(word)
build()
rows.pop()
build()
return squares