Determine Whether a Word Exists in a Graph
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in graph algorithms and backtracking techniques, including traversal strategies, cycle avoidance, and state management for matching a target sequence within a graph.
Constraints
- 0 <= len(nodes) <= 200
- 0 <= len(target) <= 15
- Each node is represented as (value, neighbors), where value is a single-character string
- Each neighbor index is a valid index into nodes
- The graph is directed and may contain cycles and repeated characters
- A node cannot be reused within the same matched path
Examples
Input: ([('C', [1]), ('A', [2]), ('T', [])], 'CAT')
Expected Output: True
Explanation: Starting at node 0 gives the path 0 -> 1 -> 2, which spells C-A-T.
Input: ([('X', [1]), ('A', [2]), ('B', []), ('A', [4]), ('B', [])], 'AB')
Expected Output: True
Explanation: The target can start from any node. For example, node 1 -> node 2 spells A-B.
Input: ([('A', [1]), ('B', [2]), ('A', [0, 3]), ('C', [])], 'ABAC')
Expected Output: True
Explanation: A valid path is 0 -> 1 -> 2 -> 3, which spells A-B-A-C. The graph contains a cycle, but the path does not reuse nodes.
Input: ([('A', [0])], 'AA')
Expected Output: False
Explanation: Even though there is a self-loop, the same node cannot be reused in one attempted match.
Input: ([], '')
Expected Output: True
Explanation: The empty string is considered matched trivially.
Input: ([('A', [1]), ('B', []), ('A', [])], 'BA')
Expected Output: False
Explanation: You can start at node 1 for 'B', but it has no outgoing edge to any 'A' node, so no valid path exists.
Hints
- Try starting a DFS/backtracking search from every node whose character matches the first character of the target.
- Use a visited set or array for the current path so cycles do not cause infinite loops and the same node is not reused.