← 返回 walmartlabs 的题目列表Merge Intervals Returning Original Start/End Indices
类型:qbank
Given a list of intervals, return the merged intervals along with the start and end original indices that contributed to each merged span. The HackerRank harness expects printed output with the contributing indices, so I/O wiring is part of the round.
Requirements
Input: intervals: int[][], each [start, end].
Merge overlapping or touching intervals. For each merged span, also report the smallest and largest original input indices that participated in the merge.
Output one line per merged interval: merged_start merged_end first_input_idx last_input_idx (exact format depends on harness; print test cases before returning).
Examples
Input intervals (with input index):
0: [1,3]
1: [2,6]
2: [8,10]
3: [15,18]
Merged:
[1,6] from input indices 0..1
[8,10] from input index 2..2
[15,18] from input index 3..3
Notes
Pair each input interval with its original index, sort by start, then sweep. Track currentStart, currentEnd, firstIdx, lastIdx. Extend currentEnd = max(currentEnd, next.end) and update lastIdx = max(lastIdx, next.origIdx) whenever the next interval overlaps; otherwise emit and reset.
Touching vs. overlapping is an explicit clarifier — [1,3] and [3,5] may or may not merge depending on whether endpoints are inclusive on both sides. The reported variant treated touching as merging.
The HackerRank harness was a noticeable cost in this round: candidates lost minutes wiring Scanner reads and println formatting. Practice the read-loop and the output formatter on the platform once before the interview rather than improvising.
firstIdx is just the original index of the first interval in the merged group after sorting by start, but only if you preserve original indices through the sort. Forgetting to attach the index before sorting is the dominant bug.
Preparation
Implement the standard merge first (returning int[][]), then layer the index tracking on top. Splitting the change makes debugging easier when the harness output is wrong.
Pre-write a tiny HackerRank main template that reads n followed by n lines of two ints and prints start end firstIdx lastIdx per merged span. Save it locally; it removes 5-10 minutes of I/O friction in the actual round.
Cover three edge cases: a single interval; fully nested intervals where one swallows several others; and pre-sorted input (verify the sort by start handles equal starts correctly).