Blind 75
63 / 75Free practice

Insert Interval

Medium · Intervals

Jump to code

Insert a closed interval into a list of closed intervals already sorted by start and mutually non-overlapping. Merge overlaps and return a sorted result. Touching endpoints overlap.

Examples

Example 1

intervals = [[1,3],[6,9]]
newInterval = [2,5]

Output: [[1,5],[6,9]]

Example 2

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
newInterval = [4,8]

Output: [[1,2],[3,10],[12,16]]

Constraints

  • 0 <= intervals.length <= 1000
  • newInterval.length == intervals[i].length == 2
  • 0 <= start <= end <= 1000
Need a hint?

Separate intervals into before, overlapping, and after the new interval.

Real interval interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      3
    ],
    [
      6,
      9
    ]
  ],
  [
    2,
    5
  ]
]
Expected
[
  [
    1,
    5
  ],
  [
    6,
    9
  ]
]
Case 2
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      5
    ],
    [
      6,
      7
    ],
    [
      8,
      10
    ],
    [
      12,
      16
    ]
  ],
  [
    4,
    8
  ]
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    10
  ],
  [
    12,
    16
  ]
]
Case 3
Input
[
  [
    [
      3,
      5
    ],
    [
      7,
      9
    ]
  ],
  [
    1,
    2
  ]
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    5
  ],
  [
    7,
    9
  ]
]
Case 4
Input
[
  [
    [
      1,
      5
    ]
  ],
  [
    2,
    3
  ]
]
Expected
[
  [
    1,
    5
  ]
]
Case 5
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ],
  [
    5,
    6
  ]
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    4
  ],
  [
    5,
    6
  ]
]

Drafts are saved per language in this browser when storage is available.