Word Squares - Problem

Imagine you're creating a word crossword puzzle where words read the same both horizontally and vertically! Given an array of unique strings words, you need to find all possible word squares you can build.

A word square is a sequence of strings where the kth row and kth column read exactly the same string. Think of it as a perfect symmetric grid where grid[i][j] == grid[j][i] for all positions.

Example: The words ["ball", "area", "lead", "lady"] form a valid word square:

b a l l
a r e a
l e a d
l a d y

Notice how column 0 reads "ball" (same as row 0), column 1 reads "area" (same as row 1), and so on!

Goal: Return all possible word squares you can construct. The same word can be used multiple times, and order doesn't matter.

Input & Output

example_1.py โ€” Basic Word Square
$ Input: ["area", "lead", "wall", "lady", "ball"]
โ€บ Output: [["ball", "area", "lead", "lady"]]
๐Ÿ’ก Note: Only one valid word square can be formed: 'ball', 'area', 'lead', 'lady'. Notice how each row reads the same as its corresponding column.
example_2.py โ€” Multiple Solutions
$ Input: ["abat", "baba", "atan", "atal"]
โ€บ Output: [["baba", "abat", "baba", "atan"], ["baba", "abat", "baba", "atal"]]
๐Ÿ’ก Note: Two valid word squares exist with these words. The word 'baba' can be used multiple times to create different valid arrangements.
example_3.py โ€” No Solution
$ Input: ["abc", "def", "ghi"]
โ€บ Output: []
๐Ÿ’ก Note: No valid word square can be formed because none of these words can satisfy the constraint that row[i] must equal column[i].

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n * k^k)

n words, k^k possible squares of size k, but heavy pruning reduces actual complexity

n
2n
โœ“ Linear Growth
Space Complexity
O(n * k + k^2)

Prefix map storage plus recursion stack and current square

n
2n
โšก Linearithmic Space

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 the strings of words are unique
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen