Word Squares II Problem
Description
LeetCode Problem 3799.
You are given a string array words, consisting of distinct 4-letter strings, each containing lowercase English letters.
A word square consists of 4 distinct words: top, left, right and bottom, arranged as follows:
topforms the top row.bottomforms the bottom row.leftforms the left column (top to bottom).rightforms the right column (top to bottom).
It must satisfy:
top[0] == left[0],top[3] == right[0]bottom[0] == left[3],bottom[3] == right[3]
Return all valid distinct word squares, sorted in ascending lexicographic order by the 4-tuple (top, left, right, bottom).
Example 1:
Input: words = ["able","area","echo","also"]
Output: [["able","area","echo","also"],["area","able","also","echo"]]
Explanation:
There are exactly two valid 4-word squares that satisfy all corner constraints:
- "able" (top), "area" (left), "echo" (right), "also" (bottom)
- top[0] == left[0] == 'a'
- top[3] == right[0] == 'e'
- bottom[0] == left[3] == 'a'
- bottom[3] == right[3] == 'o'
- "area" (top), "able" (left), "also" (right), "echo" (bottom)
- All corner constraints are satisfied.
Thus, the answer is [["able","area","echo","also"],["area","able","also","echo"]].
Example 2:
Input: words = ["code","cafe","eden","edge"]
Output: []
Explanation:
No combination of four words satisfies all four corner constraints. Thus, the answer is empty array [].
Constraints:
4 <= words.length <= 15words[i].length == 4words[i]consists of only lowercase English letters.- All
words[i]are distinct.
Solution
Approach: Enumerate Four Indices
There are at most 15 distinct words, so we can try every ordered choice of four different indices. Sort the words first, then pick top, left, right and bottom with four nested loops. Because the loops follow sorted order, the squares come out already sorted by (top, left, right, bottom). Keep a tuple when the four corner letters match.
Complexity: Time O(n^4), space O(1) besides the output, where n is the number of words (at most 15).
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
words.sort()
n = len(words)
ans = []
for i in range(n):
top = words[i]
for j in range(n):
if j != i:
left = words[j]
for k in range(n):
if k != j and k != i:
right = words[k]
for h in range(n):
if h != k and h != j and h != i:
bottom = words[h]
if (
top[0] == left[0]
and top[3] == right[0]
and bottom[0] == left[3]
and bottom[3] == right[3]
):
ans.append([top, left, right, bottom])
return ans