Debugging challengeBeginner
Sorted numbers in the wrong order
Scenario
A k-th smallest helper and a "meeting rooms" interval merge both sort their input first. Tests with single-digit numbers pass, but kthSmallest([10, 2, 5, 33, 4], 1) returns 10 and the interval merge produces overlapping output when start times exceed 9. Find the bug.
1function kthSmallest(nums, k) {2 const sorted = [...nums].sort();3 return sorted[k - 1];4}5 6function mergeIntervals(intervals) {7 intervals.sort();8 const out = [];9 for (const [s, e] of intervals) {10 if (out.length && out[out.length - 1][1] >= s) {11 out[out.length - 1][1] = Math.max(out[out.length - 1][1], e);12 } else {13 out.push([s, e]);14 }15 }16 return out;17}18 19console.log(kthSmallest([10, 2, 5, 33, 4], 1)); // 10, expected 220console.log(mergeIntervals([[10, 12], [2, 11], [1, 3]])); // [[1,3],[10,12],[2,11]], expected [[1,3],[2,12]] merged → [[1,12]]Your task
- What does
Array.prototype.sort()do when called with no comparator? Show what[10, 2, 5, 33, 4].sort()actually returns. - Explain why the interval merge is still wrong even though the arrays are "sorted".
- Write correct comparators for both functions. What must a comparator return?
- What happens with negative numbers,
NaN,undefinedand mixed-type arrays? - State the complexity and whether
sortis stable.
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.