Sorting by start was the obvious first move and I got there quickly.
Start by sorting the intervals by their start value, then iterate through them while merging overlapping or adjacent intervals into a result list. Track the total covered length by summing the lengths of merged intervals, being careful to handle adjacency (where end == next start) as a merge condition.
Pro tip: Explicitly clarify that 'directly adjacent' means intervals like [1,3) and [3,5) should merge, and mention that you'll handle edge cases like empty input or single interval. This shows attention to detail and prevents misinterpretation.
Confirm that adjacency (end == start) counts as overlap, and discuss handling of empty input, single interval, and negative numbers. This ensures alignment with the interviewer.
Sort the list of intervals by their start value. This is crucial for the linear scan approach and ensures O(n log n) time complexity.
Initialize a result list with the first interval. For each subsequent interval, if it overlaps or is adjacent to the last interval in the result (i.e., its start <= last end), merge them by updating the last interval's end to the maximum of both ends. Otherwise, add it to the result.
After merging, iterate through the merged intervals and sum (end - start) for each. Alternatively, accumulate the length during the merge process to avoid a second pass.
Return the merged list sorted by start (which it already is) and the total length. Discuss time and space complexity: O(n log n) time due to sorting, O(n) space for the result.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.