Check Whether a Node Sequence Is a Valid BFS on a Tree
Trees & GraphsModel answerLast 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
nup to2 × 10^5. qqueries, each of lengthn.- Aim for
O(n)per query (totalO(n + q · n)). A naiveO(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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation: order is its own queue
In any BFS, the output sequence and the FIFO queue hold exactly the same elements in the same order, because each node is recorded the moment it is enqueued and dequeued in that same FIFO sequence. This means the queue at step i is always the suffix order[i+1 .. j-1], where j is the index of the next slot not yet filled. No explicit queue needs to be maintained — order already encodes it.
The block-matching rule
When order[i] is dequeued, the BFS must immediately enqueue all of its unvisited neighbors. Because the queue is FIFO, those neighbors land in positions order[j .. j+c-1], where c is the count of unvisited neighbors. The internal order within that block is free (any neighbor ordering is allowed), but the set must match exactly. A valid BFS order passes this check at every i; an invalid one fails at least one step.
Efficiently checking each block
A naive set-comparison per step would be fine on its own, but clearing a visited array of size n between queries costs O(n) each time. To avoid that, use a stamp trick: maintain a global integer counter. To "tag" the unvisited neighbors of order[i], set tag[neighbor] = current_stamp. Verify each position in the block by checking tag[order[j..j+c-1]] == current_stamp and that the node has not already been visited in this query. Increment the counter before each node's neighborhood scan. This eliminates all per-query reset cost.
Algorithm
- Map all node labels to
0..n-1with a dictionary. - Build adjacency lists.
- For each query:
- Translate labels to internal ids; reject immediately on unknown label or wrong length.
- Mark
ids[0]as visited. Setj = 1. - For
ifrom0ton-1:- If
i >= j, the queue emptied before all nodes were processed — invalid. - Increment stamp. Tag each unvisited neighbor of
ids[i]; count them asc. - Check that
ids[j .. j+c-1]is exactly the tagged set: each element must carry the current stamp and not already be visited in this query. - Mark those elements visited. Advance
j += c.
- If
- If all checks pass, the query is valid.
Complexity
- Preprocessing:
O(n)to build the label map and adjacency lists. - Per query:
O(n), since each node is processed once and the sum of degrees is2(n-1). Block checking is also proportional to the block size, which sums ton-1across all steps. - Total:
O(n + q · n). - Space:
O(n)for adjacency lists, visited, and tag arrays (reused across queries).
Edge cases
n = 1: no edges, no array entries. Any single-element query is valid.- Unknown or duplicate labels in a query: an unknown label fails the dictionary lookup; a duplicate is already marked visited when it appears the second time, so the block check fails.
- Star tree: the root's entire neighborhood forms one block of size
n-1, then every subsequent step produces an empty block. Handled uniformly. - Path tree: every block has size 0 or 1. Also handled uniformly.
- Queue empties early (
i == j): this would mean a node was dequeued but no neighbors were added and not all nodes have been seen. In a connected tree this can only happen if a prior block check incorrectly accepted a subset — which the check prevents — but the guardi >= jcatches any such case defensively.
Common mistakes
- Checking only BFS levels. Verifying that depths are non-decreasing is necessary but not sufficient. A sequence where node B's children appear before node A's children (even though A was dequeued before B) will pass a level check but fail the block check.
- Running a full BFS and comparing. Sorting each adjacency list by position in
orderand running BFS is correct but costsO(n log n)per query. The block approach is strictly faster. - Forgetting non-contiguous or large labels. Assuming labels are
1..nbreaks on arbitrary integers; the label-mapping step is required.
Python implementation
from typing import List
def check_bfs_orderings(
u: List[int], v: List[int], queries: List[List[int]]
) -> List[bool]:
# --- build label map ---
idx: dict[int, int] = {}
for a, b in zip(u, v):
if a not in idx:
idx[a] = len(idx)
if b not in idx:
idx[b] = len(idx)
# single-node tree: no edges given, any length-1 query is valid
if not u:
return [len(order) == 1 for order in queries]
n = len(idx)
adj: List[List[int]] = [[] for _ in range(n)]
for a, b in zip(u, v):
ia, ib = idx[a], idx[b]
adj[ia].append(ib)
adj[ib].append(ia)
# visited[x] == qi means node x was visited during query qi
visited = [-1] * n
# tag[x] == stamp means x is a pending child of the current node
tag = [-1] * n
stamp = 0
results: List[bool] = []
for qi, order in enumerate(queries):
if len(order) != n:
results.append(False)
continue
# translate labels; bail on unknown
ids: List[int] = []
ok = True
for label in order:
k = idx.get(label)
if k is None:
ok = False
break
ids.append(k)
if not ok:
results.append(False)
continue
visited[ids[0]] = qi
j = 1 # next unfilled position in the implicit queue
for i in range(n):
if i >= j: # queue exhausted before all nodes seen
ok = False
break
x = ids[i]
stamp += 1
c = 0 # number of unvisited neighbors
for w in adj[x]:
if visited[w] != qi:
tag[w] = stamp
c += 1
if j + c > n: # block would exceed array bounds
ok = False
break
# verify the next c positions form exactly the tagged set
for p in range(j, j + c):
y = ids[p]
if tag[y] != stamp or visited[y] == qi:
ok = False
break
visited[y] = qi
if not ok:
break
j += c
results.append(ok)
return results
Walkthrough on the example
Edges: (1,3), (1,2), (4,3). Query: [1, 2, 3, 4].
| Step | Dequeue | Unvisited neighbors | Expected block | Block in order | Pass? |
|---|---|---|---|---|---|
| i=0 | 1 | {2, 3}, c=2 | order[1..2] | [2, 3] | ✓ |
| i=1 | 2 | none, c=0 | empty | — | ✓ |
| i=2 | 3 | {4}, c=1 | order[3..3] | [4] | ✓ |
| i=3 | 4 | none, c=0 | empty | — | ✓ |
Result: true.
For [1, 2, 4, 3]: at i=0, the block is [2, 4]. Node 4 is not adjacent to 1, so tag[4] != stamp. Result: false.