Find Words in a Character Grid
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates algorithm design for efficient multi-word search in a character grid, testing competencies in constrained graph traversal, managing large dictionaries, and selecting data structures for efficient lookup.
Constraints
- 1 <= len(board), len(board[0]) <= 12
- 1 <= len(words) <= 30000
- 1 <= len(words[i]) <= 10
- All board cells and words contain only lowercase English letters
Examples
Input: ([['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']], ['oath','pea','eat','rain'])
Expected Output: ['eat', 'oath']
Explanation: The words 'oath' and 'eat' can be formed by valid adjacent paths. 'pea' and 'rain' cannot.
Input: ([['a']], ['a','aa','b','a'])
Expected Output: ['a']
Explanation: Only 'a' can be formed. 'aa' would require reusing the same cell, and duplicates should appear only once in the result.
Hints
- Searching the full grid separately for every word repeats a lot of work. Think about a data structure that groups words by shared prefixes.
- While doing DFS from the board, stop exploring as soon as the current path is not a prefix of any remaining dictionary word.