LeetCode 57: Insert Interval Solution

Master LeetCode problem 57 (Insert Interval), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

57. Insert Interval

Medium

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the given intervals and newInterval and merge them in a sorted manner. We can follow these steps:

  1. Initialize an empty list to store the merged intervals.
  2. Iterate through the intervals and newInterval and merge them based on the overlapping conditions.
  3. Add non-overlapping intervals directly to the result list.
  4. Return the merged list of intervals.

Time Complexity: O(n), where n is the number of intervals in the input list. Space Complexity: O(n), to store the merged intervals.

:

Solution Code

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> result = new ArrayList<>();
        int i = 0;
        
        while (i < intervals.length && intervals[i][1] < newInterval[0]) {
            result.add(intervals[i]);
            i++;
        }
        
        while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
            newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
            newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
            i++;
        }
        
        result.add(newInterval);
        
        while (i < intervals.length) {
            result.add(intervals[i]);
            i++;
        }
        
        return result.toArray(new int[result.size()][]);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 57 (Insert Interval)?

This page provides optimized solutions for LeetCode problem 57 (Insert Interval) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 57 (Insert Interval)?

The time complexity for LeetCode 57 (Insert Interval) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 57 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 57 in Java, C++, or Python.

Back to LeetCode Solutions