← Questions

Does a word exist as a path in a graph?

0
GoogleCodingLast asked May 2026

A coding interview question asked in Google's onsite coding round, last asked May 2026. It tests graphs, dfs and backtracking.

Every node of an undirected graph holds one letter. Decide whether a given word can be spelled by walking along edges, one letter per node, starting at any node. By default a node may not be used twice in the same word.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • word_exists(letters: dict[int, str], edges: list[tuple[int, int]], word: str) -> bool — letters[v] is the letter on node v.

Example

Nodes 1:'c', 2:'a', 3:'t', 4:'s'; edges 1-2, 2-3, 3-4, 2-4.

word_exists(letters, edges, "cat")   ->  True     # 1 -> 2 -> 3
word_exists(letters, edges, "cats")  ->  True     # 1 -> 2 -> 3 -> 4
word_exists(letters, edges, "cast")  ->  True     # 1 -> 2 -> 4 -> 3
word_exists(letters, edges, "tat")   ->  False    # would need node 3 twice

If nodes may be reused, "tat" becomes True (3 -> 2 -> 3).

Constraints

  • Up to 10^4 nodes and 5 * 10^4 edges; words up to 20 letters.
  • Several nodes may hold the same letter.

Clarifying questions

  • May a node be used more than once in the same word? May the walk go back along the edge it just used?
  • Is the graph directed?
  • One word, or many words against the same graph?
  • Case-sensitive?

What a strong answer covers

  • Backtracking DFS from every node whose letter matches the first character, extending only to neighbours with the next letter, with a visited set that is undone on return.
  • Cost: O(V * b^(L-1)) in the worst case, where b is the branching factor and L the word length; pruning by letter usually cuts this a lot.
  • With reuse allowed, the state is just (node, index), so memoisation or a BFS over those states gives O((V + E) * L).
  • Tests: single-letter word, word longer than the graph, repeated letters, disconnected graph.

Follow-ups

  • Find all dictionary words that exist in the graph (a trie over the words, as in Word Search II).
  • Return the path for a found word.
  • The graph is huge and stored on disk: which index on letters helps?

Where it's asked

  • Google · Onsite coding · Last asked May 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

graphs · dfs · backtracking

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding