LeetCode 436: Find Right Interval Solution
Master LeetCode problem 436 (Find Right 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.
436. Find Right Interval
Problem Explanation
Explanation:
To solve this problem, we can first sort the intervals based on their start points. Then, for each interval, we can perform a binary search to find the right interval by looking for the smallest start point that is greater than or equal to the current interval's end point.
- Sort the intervals based on their start points.
- For each interval, perform a binary search on the sorted intervals to find the right interval.
- If a right interval is found, store its index in the result array. Otherwise, store -1.
Time complexity: O(n log n) where n is the number of intervals (due to sorting and binary searching) Space complexity: O(n) for storing the result array
:
Solution Code
class Solution {
public int[] findRightInterval(int[][] intervals) {
TreeMap<Integer, Integer> map = new TreeMap<>();
int n = intervals.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
map.put(intervals[i][0], i);
}
for (int i = 0; i < n; i++) {
Map.Entry<Integer, Integer> entry = map.ceilingEntry(intervals[i][1]);
result[i] = (entry != null) ? entry.getValue() : -1;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 436 (Find Right Interval)?
This page provides optimized solutions for LeetCode problem 436 (Find Right 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 436 (Find Right Interval)?
The time complexity for LeetCode 436 (Find Right Interval) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 436 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 436 in Java, C++, or Python.