← Accenture bank

Accenture · Question 62 · Backtracking

Word Search II

BacktrackingC++code⏱ O(M * N * 4^L)💾 O(K * L)
Service-based

Problem

Given a 2D board and a list of words, find all words in the board.

Approach

Use Trie and DFS for efficient search.

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

How it works

  1. 1Index all words in a Trie.
  2. 2DFS follows Trie edges only; driver sorts for stability.

Sample input / output

Input:
board = 4x4 (oath grid), words = ["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 3Branches 5Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoyes↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <string>include <unordered_set>include <algorithm>using namespace stdCLASS TrieNodeTrieNode* children[26] = {}std::string word = ""DEFINE insertWord(TrieNode*root, const std::string&word)TrieNode* node = rootfor (char c : word)DEFINE idx = c - 'a'if(!node->children[idx])node->children[idx] …node = node->children[idx]node->word = wordDEFINEdfs(vector<vector<char>>&board, int i, int j…DEFINE c = board[i][j]if (c == '#' ||!node->children[c -'a']) returnnode = node->children[c -'a']if(!node->word.empty())res.push_back(node->word)node->word = ""board[i][j] = '#'DEFINE int dirs[4][2] ={{1, 0}, {-1, 0}, {0, 1},{0, -1}}for (auto& d : dirs)DEFINE ni = i + d[0], nj =j + d[1]if (ni >= 0 && ni <(int)board.size() &&nj >= 0 && nj …dfs(board, ni, nj, node,res)board[i][j] = cvector<string>findWords(vector<vector<char>>&board, vector<string>…DEFINE main()vector<vector<char>> board={{'o','a','a','n'},{'e','t','a','e'},vector<string> words ={"oath", "pea", "eat","rain"}auto r = findWords(board,words)sort(r.begin(), r.end())cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << r[i]cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/43

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