Word Squares II

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:

  • top forms the top row.
  • bottom forms the bottom row.
  • left forms the left column from top to bottom.
  • right forms the right column from 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
Inputwords = ["able","area","echo","also"]
Output[["able","area","echo","also"],["area","able","also","echo"]]
There are exactly two valid 4-word squares that satisfy all corner constraints, so both are returned in lexicographic order.
Example 2
Inputwords = ["code","cafe","eden","edge"]
Output[]
No combination of four words satisfies all four corner constraints, so the answer is an empty array.

Constraints

  • 4 <= words.length <= 15
  • words[i].length == 4
  • words[i] consists of only lowercase English letters.
  • All words[i] are distinct.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate