Coders Crushby Napplied AI
Back to DSA Problems
HardTries

Word Search II

Search words in grid using trie

Solution Approach

Build trie from words. DFS on board, backtrack to find all valid words.

Implementation
def findWords(board, words):
    trie = {}
    for word in words:
        node = trie
        for char in word:
            node = node.setdefault(char, {})
        node["$"] = word
    
    result = []
    visited = set()
    
    def dfs(i, j, node):
        if "$" in node:
            result.append(node["$"])
            del node["$"]
        
        for di, dj in [(0,1), (1,0), (0,-1), (-1,0)]:
            ni, nj = i + di, j + dj
            if 0 <= ni < len(board) and 0 <= nj < len(board[0]):
                if (ni, nj) not in visited and board[ni][nj] in node:
                    visited.add((ni, nj))
                    dfs(ni, nj, node[board[ni][nj]])
                    visited.remove((ni, nj))
    
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] in trie:
                visited.add((i, j))
                dfs(i, j, trie[board[i][j]])
                visited.remove((i, j))
    
    return result
Complexity Analysis

Time Complexity

O(m*n*4^L)

Space Complexity

O(t)
Complexity
Time:O(m*n*4^L)
Space:O(t)
Asked at
GoogleAmazon
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless