Find Words in Grid

hardcodingAlgorithmsGraphs

Overview

Given an m × n board of characters and a list of words, return all words that can be formed on the board.

Each word must be constructed from letters of sequentially adjacent cells (horizontally or vertically). A cell cannot be reused within a single word, but can be reused across different words.

Implement findWords(board, words).

Constraints

  • board is a 2D array of lowercase letters.
  • words is an array of lowercase strings.
  • Same cell cannot be used twice in one word path.
  • Return words in any order, with no duplicates.
  • Naive approach (run word-search per word) is too slow — use a Trie for $O(m \times n \times 4^L)$ total instead of $O(W \times m \times n \times 4^L)$.

Examples

const board = [
  ["o","a","a","n"],
  ["e","t","a","e"],
  ["i","h","k","r"],
  ["i","f","l","v"]
];

findWords(board, ["oath","pea","eat","rain"]);
// → ["eat", "oath"]  (any order)
findWords([["a","b"],["c","d"]], ["abcb"]);
// → []  — can't reuse cells

Notes

  • Trie + backtracking: Build a Trie from the word list. Then DFS from every cell, walking the Trie in parallel. When you reach a Trie node that marks a complete word, record it.
  • Prune Trie nodes after finding a word to avoid duplicate results and speed up future searches.
  • This is significantly faster than running the single-word search for each word independently.

Solution

Reveal solution
function findWords(board, words) {
  const root = {};
  for (const w of words) {
    let node = root;
    for (const ch of w) {
      if (!node[ch]) node[ch] = {};
      node = node[ch];
    }
    node.word = w;
  }

  const rows = board.length, cols = board[0].length;
  const result = [];

  function dfs(r, c, node) {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return;
    const ch = board[r][c];
    if (ch === "#" || !node[ch]) return;

    const next = node[ch];
    if (next.word) {
      result.push(next.word);
      delete next.word; // avoid duplicates
    }

    board[r][c] = "#";
    dfs(r + 1, c, next);
    dfs(r - 1, c, next);
    dfs(r, c + 1, next);
    dfs(r, c - 1, next);
    board[r][c] = ch;
  }

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      dfs(r, c, root);
    }
  }

  return result;
}

Resources

NameTopicDifficulty
Add BinaryAlgorithmseasyBalanced Binary TreeAlgorithmseasyBalanced BracketsAlgorithmseasyBinary SearchAlgorithmseasyBinary Search Tree Lowest Common AncestorAlgorithmseasyBinary Tree Maximum DepthAlgorithmseasyBinary Tree SubtreeAlgorithmseasyBit CountingAlgorithmseasyBit ReversalAlgorithmseasyCount Set Bits in a Binary NumberAlgorithmseasyDiameter of Binary TreeAlgorithmseasyFind Duplicates in ArrayAlgorithmseasyFirst Bad VersionAlgorithmseasyFlip Binary TreeAlgorithmseasyFlood FillAlgorithmseasyLinked List Detect CycleAlgorithmseasyLinked List ReversalAlgorithmseasyLinked Lists Combine Two SortedAlgorithmseasyLongest PalindromeAlgorithmseasyMiddle of the Linked ListAlgorithmseasyMost Common ElementsAlgorithmseasyOptimal Stock TradingAlgorithmseasyPair SumAlgorithmseasyRansom NoteAlgorithmseasyStaircase Climbing CombinationsAlgorithmseasyString AnagramAlgorithmseasyString PalindromeAlgorithmseasy01 MatrixAlgorithmsmediumAccounts MergeAlgorithmsmediumArray Product Excluding CurrentAlgorithmsmediumBinary Search Tree Kth Smallest ElementAlgorithmsmediumBinary Tree Level Order TraversalAlgorithmsmediumBinary Tree Rebuilding from Preorder and Inorder TraversalsAlgorithmsmediumBinary Tree Right Side ViewAlgorithmsmediumCombinations for Target SumAlgorithmsmediumCount Islands in a GridAlgorithmsmediumCourse DependencyAlgorithmsmediumDecode MessageAlgorithmsmediumDisjoint IntervalsAlgorithmsmediumDistinct Paths in GridAlgorithmsmediumEvaluate Reverse Polish NotationAlgorithmsmediumFind All Anagrams in a StringAlgorithmsmediumFind Element in Rotated ArrayAlgorithmsmediumFind the Longest Palindromic SubstringAlgorithmsmediumFind Word in GridAlgorithmsmediumGraph CloneAlgorithmsmediumGraph Count Connected ComponentsAlgorithmsmediumIs the Graph a TreeAlgorithmsmediumK Closest Points to OriginAlgorithmsmediumLetter Combinations of a Phone NumberAlgorithmsmediumLongest Increasing SubsequenceAlgorithmsmediumLongest Non-repeating SubstringAlgorithmsmediumLongest Repeating Substring After ReplacementsAlgorithmsmediumLowest Common Ancestor of a Binary TreeAlgorithmsmediumMatrix RotationAlgorithmsmediumMatrix Spiral TraversalAlgorithmsmediumMatrix ZeroingAlgorithmsmediumMaximum Sum in Contiguous ArrayAlgorithmsmediumMaximum Water Trapped Between WallsAlgorithmsmediumMerge New IntervalAlgorithmsmediumMerge Overlapping IntervalsAlgorithmsmediumMinimum Coins for ChangeAlgorithmsmediumMinimum Height TreesAlgorithmsmediumPalindromic SubstringsAlgorithmsmediumPartition Equal Subset SumAlgorithmsmediumPermutationsAlgorithmsmediumRotting OrangesAlgorithmsmediumSegment WordsAlgorithmsmediumSort ColorsAlgorithmsmediumString Anagram GroupsAlgorithmsmediumString to Integer (atoi)AlgorithmsmediumSubsetsAlgorithmsmediumSum Without AdditionAlgorithmsmediumTask CoordinationAlgorithmsmediumTrie (Prefix Tree)AlgorithmsmediumTriplet SumAlgorithmsmediumValidate Binary Search TreeAlgorithmsmediumBasic CalculatorAlgorithmshardBinary Tree EqualAlgorithmshardBinary Tree Maximum Total PathAlgorithmshardDelete Nth Node from End of Linked ListAlgorithmshardEnd of Array ReachableAlgorithmshardExtraterrestrial LanguageAlgorithmshardFind Missing Number in SequenceAlgorithmshardFind Words in GridAlgorithmshardLargest Rectangle in HistogramAlgorithmshardLinked Lists Combine K SortedAlgorithmshardLongest Common SubsequenceAlgorithmshardLongest Consecutive Number SequenceAlgorithmshardMaximum Product in Contiguous ArrayAlgorithmshardMaximum Profit in Job SchedulingAlgorithmshardMeeting CalendarAlgorithmshardMinimum Meeting Rooms NeededAlgorithmshardNeighborhood TheftAlgorithmshardNeighborhood Theft (Circular)AlgorithmshardNumber Stream MedianAlgorithmshardOcean FlowAlgorithmshardRearrange Linked ListAlgorithmshardShortest Substring Containing CharactersAlgorithmshardSmallest Element in Rotated Sorted ArrayAlgorithmshardTrapping Rain WaterAlgorithmshardWord FinderAlgorithmshardWord LadderAlgorithmshard
103 of 103 problems