Debugging challengeBeginner

The non-null assertion that lied

Scenario

A BFS over string-keyed graphs compiles clean under strict: true. At runtime, building the adjacency map throws TypeError: Cannot read properties of undefined (reading 'push') on the very first edge. A teammate "fixed" it by pre-seeding the map, and now every distance except the source comes out as NaN. Both failures trace back to the same character. Find it.

1function buildAdj(edges: [string, string][]): Map<string, string[]> {
2 const adj = new Map<string, string[]>();
3 for (const [a, b] of edges) {
4 adj.get(a)!.push(b); // TypeError on the first edge
5 adj.get(b)!.push(a);
6 }
7 return adj;
8}
9
10function bfsDist(adj: Map<string, string[]>, src: string): Map<string, number> {
11 const dist = new Map<string, number>();
12 dist.set(src, 0);
13 const queue: string[] = [src];
14 let head = 0;
15 while (head < queue.length) {
16 const u = queue[head++];
17 for (const v of adj.get(u)!) {
18 if (!dist.has(v)) {
19 dist.set(v, dist.get(v)! + 1); // meant dist.get(u) — v is not in the map yet
20 queue.push(v);
21 }
22 }
23 }
24 return dist;
25}
26
27// after seeding adj by hand:
28// bfsDist(adj, 'a') → Map { 'a' → 0, 'b' → NaN, 'c' → NaN }

Your task

  1. What is the return type of Map.get() and what does the ! operator tell the compiler? What code does ! emit at runtime?
  2. Explain the crash in buildAdj and why tsc accepted the line.
  3. In bfsDist, dist.get(v)! + 1 produces NaN instead of throwing. Walk through the JavaScript semantics that make that happen, and find the typo the ! concealed.
  4. Rewrite both functions without any !. What idioms replace it (??, get-or-create, an early undefined check)?
  5. When is ! legitimate? Give one example from this exercise where an assertion would actually be justified.
DebuggingEdge CasesImplementation

Work it out

Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.

Reveal

Progressive — each section builds on the previous one.

The bug
Why it happens
The fix
Edge cases
Complexity

Self-check

Tick what your analysis covered. Be honest — this feeds your readiness profile.

0/6

Related concepts