Data Structures & AlgorithmsHardAmazon/Microsoft SDE pattern
An undirected graph has adjacency lists (neighbours visited in alphabetical order) A: [B, C, F]; B: [A, C, D]; C: [A, B]; D: [B, E, F]; E: [D, F]; F: [A, D, E]. What is the BFS traversal order starting from A?
- A. A, B, C, D, E, F
- B. E, D, F, C, B, A
- C. A, B, C, F, D, E
- D. A, F, C, B, E, D
Correct answer: C. A, B, C, F, D, E
BFS visits A, enqueues its unvisited neighbours in sorted order, then repeatedly dequeues the front of the queue and enqueues its unvisited neighbours, giving A, B, C, F, D, E. A DFS from the same start and adjacency lists would instead give A, B, C, D, E, F, since DFS dives down one branch before backtracking.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What are the time complexities of P and Q? c int P(int n) { if (n <= 1) return 1; return P(n/2) + P(n/2) + n; } int Q(int n) { if (n <= 1)…
- Undirected graph edges: E–D, E–C, A–C, D–C, B–A, B–E, B–D. Using a BFS 2-colouring, is this graph bipartite?
- Keys 69, 79, 89 are inserted in this order into an empty AVL tree. After AVL rebalancing (a single rotation resolves the imbalance here)…
- Keys 4, 74, 93, 84, 37, 87, 63 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a table…
- Keys 79, 74, 70, 89, 2, 6, 8 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a table…
- Keys 75, 53, 77, 17, 31, 29, 21, 5, 95 are inserted in this order into an empty BST (no rebalancing). What is the height of the tree…