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.
Input: ([['a','b'],['c','d']], ['ab','abc','abd','acdb','bdca','ab'])
Expected Output: ['ab', 'abd', 'acdb', 'bdca']
Explanation: 'ab', 'abd', 'acdb', and 'bdca' all have valid paths. 'abc' cannot be formed with orthogonal moves only.
Input: ([['x','y'],['z','w']], ['xyzwx','yzx','xx'])
Expected Output: []
Explanation: None of the words can be formed without reusing a cell or making an invalid move.
Input: ([['a','a']], ['a','aa','aaa'])
Expected Output: ['a', 'aa']
Explanation: The board can form 'a' and 'aa'. 'aaa' is impossible because the board has only two cells and a cell cannot be reused.
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.