1810. Letter Square Builder

Hard7.5 points estimatedBacktrackingTrieStringHash Table

A puzzle shop stacks letter tiles into word squares. Given words, a list of distinct lowercase words that all have the same length L. A word square is a list of L words (its rows) such that, for every i, row i read left to right equals column i read top to bottom. Words may be used more than once in the same square.

Return every word square that can be built from words. Each square is returned as its list of rows, and the squares are sorted lexicographically by their rows (compare the first row, then the second, and so on). The input guarantees that at most 100 squares exist, and an empty list is returned when there are none. Build the rows one at a time: the letters already fixed in earlier rows force the prefix of the next row, so a map from every prefix to the words starting with it keeps the search small. Time is roughly output sensitive and extra space is O(n * L).

Example 1

Input:
words = ["tea","ear","ate","rat","are"]
Output:
[["ate","tea","ear"],["rat","are","tea"],["rat","ate","tea"],["tea","ear","are"]]
Explanation:

Four stacks work: ate/tea/ear, rat/are/tea, rat/ate/tea and tea/ear/are, listed in lexicographic order of their rows.

Example 2

Input:
words = ["ab","bc","cd"]
Output:
[["ab","bc"],["bc","cd"]]
Explanation:

Row 0 and row 1 must satisfy row0[1] == row1[0], which holds for ab/bc and bc/cd only.

Example 3

Input:
words = ["abc","def"]
Output:
[]
Explanation:

No two-letter overlap can ever form a square from these words, so the result is an empty list.

Constraints

1 ≤ words.length ≤ 200

1 ≤ words[i].length ≤ 4, and all words have the same length

words[i] consists of lowercase English letters; all words are distinct

At most 100 word squares exist for the input

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n * L + output * L^2)
Space
O(n * L)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…