Squared Words
You are given an array of distinct 4-letter strings, words.
Your task is to select four different words from the array to act as the top, bottom, left, and right edges of a square boundary. To form a valid word square, the letters at the four intersecting corners of these edges must match exactly:
- Top-Left: top[0] == left[0]
- Top-Right: top[3] == right[0]
- Bottom-Left: bottom[0] == left[3]
- Bottom-Right: bottom[3] == right[3]
Find all valid combinations of [top, left, right, bottom]. Return the result as a list of arrays, sorted in ascending lexicographical order.
Example 1:
Input: words = ["bear", "bull", "roar", "liar"]
Output: [["bear", "bull", "roar", "liar"], ["bull", "bear", "liar", "roar"]]
Explanation: We can form exactly two valid distinct 4-word squares that satisfy all corner constraints. If we choose "bear" as the top word, "bull" as the left, "roar" as the right, and "liar" as the bottom, all four overlapping corners perfectly match ('b' at top-left, 'r' at top-right, 'l' at bottom-left, and 'r' at bottom-right). Alternatively, by symmetry, swapping the roles to make "bull" the top word and "bear" the left word (while setting "liar" as the right and "roar" as the bottom) also perfectly satisfies every corner condition.
Example 2:
Input: words = ["cool", "chef", "load", "find"]
Output: [["chef", "cool", "find", "load"], ["cool", "chef", "load", "find"]]
Explanation: We arrange the words to align their shared corner characters: 'c', 'l', 'f', and 'd'. If "chef" is placed at the top and "cool" on the left, "chef" ends with 'f' (meaning the right word must start with 'f', which is "find"), and "cool" ends with 'l' (meaning the bottom word must start with 'l', which is "load"). Both "find" and "load" correctly end with the letter 'd', securing the bottom-right corner. The reverse arrangement with "cool" on top also works. The output tuples are sorted in ascending lexicographical order, starting with "chef".
Now Your Turn!
Pick the correct output for the given inputInput: words = ["aaba", "acaa", "adda", "aeaa"]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 4 <= words.length <= 15
- words[i].length == 4
- All strings consist of lowercase English letters and are entirely distinct.