Word Search II

HardTries
Asked byUberAmazonCiscoMicrosoftFacebookSnapchat

Problem

Given an m x n grid of characters and a list of words, return every word from the list that can be formed by a path of adjacent cells (moving up, down, left or right) without reusing the same cell within one word.

Examples

Example 1
Input: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"]

Constraints

  • 1 <= board rows/cols <= 12
  • 1 <= words.length <= 3 * 10^4

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Tries pattern

A trie (prefix tree) stores strings character by character along tree edges, so words sharing a prefix share the same path. It turns "does any word start with this prefix?" into a walk proportional to the prefix length instead of a scan of every word.

Look for this pattern when

  • You're repeatedly checking prefixes (autocomplete, spell-check, word search on a grid).
  • You need to store a large dictionary of words and query it efficiently by prefix.

Read the full Tries guide →

Video walkthroughs

Original problem on LeetCode ↗

More Tries problems