← Microsoft bank

Microsoft · Question 68 · Backtracking

Word Search II

BacktrackingJavacode⏱ O(M×N×4^L)💾 O(K×L)
Product-based

Problem

Given a board and a list of words, find all words present in the board. You may move in 4 directions and can't revisit cells.

Approach

Trie-indexed words plus board DFS that follows Trie edges only.

Time O(M×N×4^L)Space O(K×L)

How it works

  1. 1Index all words in a Trie.
  2. 2DFS the board following Trie edges only.
  3. 3Collect words at terminal nodes; driver sorts for stability.

Sample input / output

Input:
4 4
oaan
etae
ihkr
iflv
4
oath pea eat rain
Output:
[eat, oath]

Constraints

1 <= m, n <= 12; lowercase board and words.

Solution — read it, then walk it

Time O(M×N×4^L)Space O(K×L)Loops 7Branches 3Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatyesnoyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class TrieNodeMap<Character, TrieNode>children = new HashMap<>()String word = nullDEFINE static TrieNodebuildTrie(String[] words)TrieNode root = newTrieNode()for (String word :words)TrieNode node = rootfor (char c :word.toCharArray())node =node.children.computeIfAbsent(c,k -> new TrieNode())node.word = wordRETURN rootDEFINE static List<String>findWords(char[][] board,String[] words)List<String> res = newArrayList<>()TrieNode root =buildTrie(words)DEFINE m = board.length, n= board[0].lengthfor (int i = 0; i < m;i++)for (int j = 0; j < n;j++)dfs(board, i, j, root, res)RETURN resDEFINE static voiddfs(char[][] board, int i,int j, TrieNode node…DEFINE c = board[i][j]if (c == '#' ||!node.children.containsKey(c))returnnode = node.children.get(c)if (node.word != null)res.add(node.word)node.word = nullboard[i][j] = '#'DEFINE [][] dirs = {{0, 1},{1, 0}, {0, -1}, {-1, 0}}for (int[] d : dirs)DEFINE ni = i + d[0], nj =j + d[1]if (ni >= 0 && ni <board.length && nj >=0 && nj …dfs(board, ni, nj, node,res)board[i][j] = cDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE m = sc.nextInt();int n = sc.nextInt()DEFINE [][] board = newchar[m][n]for (int i = 0; i < m;i++) board[i] =sc.next().toCharArray()DEFINE k = sc.nextInt()String[] words = newString[k]for (int i = 0; i < k;i++) words[i] =sc.next()java.util.List<String>found = findWords(board,words)Collections.sort(found)
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits