Problem · String

Word Squares

Learn this problem
HardInMobi logoInMobiFULLTIMEONSITE INTERVIEW

Problem statement

Given an array words whose strings all have the same length length, return every word square that can be formed.

A word square contains exactly length rows. For every valid pair of indices row and column, the character at row row, column column must equal the character at row column, column row.

  • Every row must be a word from words.
  • The same word may be used more than once in one square.
  • Return an empty array when no square can be formed.
  • Return the squares in lexicographic order by their row sequences.

Function

findWordSquares(words: String[]) → String[][]

Examples

Example 1

words = ["ball","area","leap","lead","lady"]return = [["ball","area","lead","lady"]]

The rows and columns both spell ball, area, lead, and lady in the same order.

Example 2

words = ["abat","baba","atan","atal"]return = [["baba","abat","baba","atal"],["baba","abat","baba","atan"]]

Both results are valid squares. The word baba is reused, which is allowed.

Example 3

words = ["abc","def","ghi"]return = []

No ordering of three provided words satisfies the row-column equality rule.

Constraints

  • 1 <= words.length <= 200
  • 1 <= words[i].length <= 5
  • All words have the same length and contain only lowercase English letters.
  • The input words are distinct.
  • The total number of returned word squares is at most 1000.

More InMobi problems

drafts saved locally
public String[][] findWordSquares(String[] words) {
    // write your code here
}
words["ball","area","leap","lead","lady"]
expected[["ball", "area", "lead", "lady"]]
checking account