js-02-merge-intervals
1.000
Proposed solution
```js
export function mergeIntervals(intervals) {
// Handle empty input
if (intervals.length === 0) {
return [];
}
// Sort intervals by start time
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
// Merge overlapping intervals
const merged = [sorted[0]];
for (let i = 1; i < sorted.length; i++) {
const current = sorted[i];
const lastMerged = merged[merged.length - 1];
// Check if current interval overlaps with the last merged interval
if (current[0] <= lastMerged[1]) {
// Merge them by updating the end time of the last merged interval
lastMerged[1] = Math.max(lastMerged[1], current[1]);
} else {
// No overlap, add current interval to merged array
merged.push(current);
}
}
return merged;
}
```Test output (stdout)
TAP version 13 # Subtest: empty input returns empty array ok 1 - empty input returns empty array --- duration_ms: 0.590393 type: 'test' ... # Subtest: single interval is returned unchanged ok 2 - single interval is returned unchanged --- duration_ms: 0.101541 type: 'test' ... # Subtest: unsorted disjoint input is sorted ok 3 - unsorted disjoint input is sorted --- duration_ms: 0.06297 type: 'test' ... # Subtest: overlapping intervals merge ok 4 - overlapping intervals merge --- duration_ms: 0.431923 type: 'test' ... # Subtest: touching endpoints merge ok 5 - touching endpoints merge --- duration_ms: 0.06675 type: 'test' ... # Subtest: containment keeps the wider interval ok 6 - containment keeps the wider interval --- duration_ms: 0.050321 type: 'test' ... # Subtest: disjoint intervals are left separate ok 7 - disjoint intervals are left separate --- duration_ms: 0.05269 type: 'test' ... # Subtest: duplicates collapse to one ok 8 - duplicates collapse to one --- duration_ms: 0.04382 type: 'test' ... # Subtest: mixed unsorted overlapping and disjoint ok 9 - mixed unsorted overlapping and disjoint --- duration_ms: 0.060631 type: 'test' ... # Subtest: the input array is not mutated ok 10 - the input array is not mutated --- duration_ms: 0.112201 type: 'test' ... 1..10 # tests 10 # suites 0 # pass 10 # fail 0 # cancelled 0 # skipped 0 # todo 0 # duration_ms 30.079493
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.