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 2
20console.log(mergeIntervals([[10, 12], [2, 11], [1, 3]])); // [[1,3],[10,12],[2,11]], expected [[1,3],[2,12]] merged → [[1,12]]

Your task

  1. What does Array.prototype.sort() do when called with no comparator? Show what [10, 2, 5, 33, 4].sort() actually returns.
  2. Explain why the interval merge is still wrong even though the arrays are "sorted".
  3. Write correct comparators for both functions. What must a comparator return?
  4. What happens with negative numbers, NaN, undefined and mixed-type arrays?
  5. State the complexity and whether sort is 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.

0/7

Related concepts