Debugging challengeBeginner
Frequency counter with an Object
Scenario
A word-frequency service uses a plain object as a hash map. Two bug reports: (1) counting the word "constructor" returns a function-like garbage value instead of a number; (2) a coordinate-visited set keyed by [row, col] treats every cell as already visited after the first one. Find both bugs.
1function wordFrequencies(words) {2 const freq = {};3 for (const w of words) {4 if (freq[w]) freq[w] += 1;5 else freq[w] = 1;6 }7 return freq;8}9 10function countReachable(grid, start) {11 const visited = {};12 const stack = [start];13 let count = 0;14 while (stack.length) {15 const cell = stack.pop();16 if (visited[cell]) continue;17 visited[cell] = true;18 count++;19 const [r, c] = cell;20 for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {21 const nr = r + dr, nc = c + dc;22 if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] === 0)23 stack.push([nr, nc]);24 }25 }26 return count;27}28 29console.log(wordFrequencies(['a', 'constructor', 'constructor']));30// { a: 1, constructor: 'function Object() { [native code] }1' } — expected 231console.log(countReachable([[0, 0], [0, 0]], [0, 0])); // 4 — looks right…32const seen = {}; seen[[1, 2]] = true;33console.log(seen[[1, 2]], seen['1,2'], Object.keys(seen)); // true true ['1,2']Your task
- Why does
freq["constructor"]start out truthy on an empty object? Name two more keys with the same problem. - What does JavaScript do with a non-string object key such as
[1, 2]? Why does the visited-set example *appear* to work, and when would it break? - Rewrite both functions with
Map/Set. What key type do they use, and how is equality determined? - If you had to keep a plain object, how would you make it safe?
- State the complexity of the fixed code.
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.