Blind 75
38 / 75Free practice

Word Search II

Hard · Tries

Jump to code

Given a rectangular letter board and a list of distinct nonempty words, return those that can be traced using horizontal or vertical neighbors. A cell cannot be reused within one word.

Examples

Example 1

board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]

Example 2

board = [["a","b"],["c","d"]]
words = ["abcb"]

Output: []

Constraints

  • 1 <= board.length, board[i].length <= 12
  • board[i] consists only of lowercase English letters.
  • 1 <= words.length <= 30,000
  • 1 <= words[i].length <= 10
  • words[i] consists only of lowercase English letters.
  • All strings within words are distinct.
Need a hint?

Share work between words with the same prefix.

Real trie interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      "o",
      "a",
      "a",
      "n"
    ],
    [
      "e",
      "t",
      "a",
      "e"
    ],
    [
      "i",
      "h",
      "k",
      "r"
    ],
    [
      "i",
      "f",
      "l",
      "v"
    ]
  ],
  [
    "oath",
    "pea",
    "eat",
    "rain"
  ]
]
Expected
[
  "eat",
  "oath"
]
Case 2
Input
[
  [
    [
      "a",
      "b"
    ],
    [
      "c",
      "d"
    ]
  ],
  [
    "abcb"
  ]
]
Expected
[]
Case 3
Input
[
  [
    [
      "a"
    ]
  ],
  [
    "a",
    "b"
  ]
]
Expected
[
  "a"
]
Case 4
Input
[
  [
    [
      "a",
      "b",
      "c"
    ],
    [
      "d",
      "e",
      "f"
    ],
    [
      "g",
      "h",
      "i"
    ]
  ],
  [
    "abe",
    "cfi",
    "adg",
    "aei"
  ]
]
Expected
[
  "abe",
  "adg",
  "cfi"
]
Case 5
Input
[
  [
    [
      "a",
      "a"
    ],
    [
      "a",
      "a"
    ]
  ],
  [
    "aa",
    "aaa",
    "aaaa"
  ]
]
Expected
[
  "aa",
  "aaa",
  "aaaa"
]

Drafts are saved per language in this browser when storage is available.