Graphs and grids · mid
Graph basics in JavaScript
Store a graph as an adjacency list: an array of arrays for numbered nodes, or a Map from id to neighbours for string ids. Use BFS for shortest paths when edges have no weights, DFS for reachability and cycles, and Kahn's algorithm (in-degrees plus a queue) for dependency order.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Adjacency list: adj = Array.from({ length: n }, () => []); for undirected edges add both directions.
- BFS shortest path (unweighted): queue + visited; mark visited when you ENQUEUE, not when you dequeue, or nodes are added many times.
- Topological sort (Kahn): count in-degrees; queue nodes with 0; pop, append, decrement neighbours; if output length < n there is a cycle.
- Cycle in a directed graph by DFS needs three colours (unvisited, in progress, done); a node seen 'in progress' means a back edge.
- Frontend links: module bundler dependency graphs, spreadsheet formula recalculation order, build pipelines, org charts (Employee Importance).
- Complexity O(V + E) for BFS, DFS and Kahn.
- There is no built-in queue or priority queue: BFS reads q[head++] instead of shift(), and Dijkstra needs a small heap you write yourself.
The red pen
Common traps: mistake → fix
Mistake: Use one visited flag for directed cycle detection
Fix: it reports false cycles for diamond shapes; use three states or Kahn.
Mistake: BFS gives shortest paths with weights
Fix: only for equal weights; weighted needs Dijkstra (a heap).
Mistake: Topological order is unique
Fix: many orders can be valid; state a tie-break rule if tests need one.
Mistake: Array(n).fill([]) makes n empty lists
Fix: it makes one list shared by every node.
Easy to hard
Questions interviewers ask, easy to hard
- Shortest number of steps between two nodes.
- Can all courses be finished given prerequisites?
- Return a valid build order for packages; what if there is a cycle?
- Recalculate spreadsheet cells after one cell changes. Which cells, in what order?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.