KatInterview

Check Whether a Node Sequence Is a Valid BFS on a Tree

Trees & GraphsModel answer
HardModel answerTrees & GraphsBFStreessimulation

Last updated

Given an undirected tree and multiple permutations of its nodes, determine for each permutation whether it could be the dequeue order of some BFS starting at its first element.

Problem

You have an undirected tree with n nodes. The tree is described by two arrays, u and v, each of length n - 1. For every index i, there is an undirected edge between u[i] and v[i]. Node labels are arbitrary integers (they may not be consecutive, and may include large or negative values).

You are given q queries. Each query is an array order of length n that contains every node label exactly once.

For each query, determine whether order could be the output produced by running a standard BFS on this tree, where:

  • The BFS starts at order[0].
  • BFS uses a standard FIFO queue.
  • Whenever a node is dequeued, all of its unvisited neighbors are enqueued — but in any order you like.
  • The recorded output is the sequence of nodes in the order they are dequeued.

Return a list of booleans, one per query.


Example

u = [1, 1, 4]
v = [3, 2, 3]

This defines edges (1,3), (1,2), and (4,3).

  • order = [1, 2, 3, 4] → true Start at 1, enqueue 2 then 3 (both are neighbors). Dequeue 2 (no new neighbors). Dequeue 3, enqueue 4. Dequeue 4. Output matches.
  • order = [1, 2, 4, 3] → false After dequeuing 1, the next two positions must be exactly {2, 3}. But position 2 contains 4, which is not a neighbor of 1.

Constraints

  • Node count n up to 2 × 10^5.
  • q queries, each of length n.
  • Aim for O(n) per query (total O(n + q · n)). A naive O(n²) per query will be too slow for large inputs.
  • Handle edge cases: n = 1 (no edges), unknown labels in a query, duplicate labels in a query.

What to produce

A working solution with the approach explained, time and space complexity analyzed, and at least the core logic implemented in code.

Hints

Hint 1

Because BFS uses a FIFO queue and the output is the dequeue order, the queue at any moment in time is always a contiguous window within `order`. You never need to maintain a separate queue data structure — `order` itself is the queue.

Hint 2

When node `order[i]` is dequeued, all of its unvisited neighbors must be added to the back of the queue right then. That means they must occupy exactly the next `c` positions in `order` (where `c` is the unvisited neighbor count), in any internal order. If the block of `c` positions does not match the unvisited neighbor set exactly, the answer is false.

Hint 3

Checking each block in O(c) without resetting an entire boolean array between queries is the key to hitting the O(n) per query target. Use an integer stamp array: tag each neighbor of the current node with the current stamp value, then verify the block entries carry that stamp. Incrementing a global counter replaces any per-query reset.