AlgoMaster Logo

Insert Interval

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Linear Scan Insertion

Intuition:

The idea is to go through the intervals and find where the newInterval should fit. We do this by keeping track of whether we are before the new interval, within it, or past it. We can add all non-merged intervals to a result list and then merge the new interval where necessary.

Code:

2. Optimal Merge Based Insertion

Intuition:

While the first solution is efficient, this slightly optimized version ensures that we're minimizing operations on the intervals by directly placing them without additional checks once the current interval doesn't overlap. The core idea remains the same, making use of efficient merging and non-overlapping checks.

Code: