LeetCode 2805: Custom Interval Solution
Master LeetCode problem 2805 (Custom 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.
2805. Custom Interval
Problem Explanation
Explanation
Given a list of intervals and a target interval, we need to insert the target interval into the list while ensuring the resulting list of intervals are non-overlapping and sorted in ascending order.
To solve this problem, we can follow these steps:
- Initialize a new list to store the resulting intervals.
- Iterate through the input list of intervals and compare each interval with the target interval to find the appropriate position to insert it.
- Merge any overlapping intervals and insert the target interval in the correct position.
- Return the resulting 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 resulting intervals.
Solution Code
import java.util.*;
class Solution {
public int[][] insertInterval(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()][2]);
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2805 (Custom Interval)?
This page provides optimized solutions for LeetCode problem 2805 (Custom 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 2805 (Custom Interval)?
The time complexity for LeetCode 2805 (Custom Interval) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2805 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2805 in Java, C++, or Python.