Find Right Interval — LeetCode 436 Python Solution

MediumArrayBinary SearchSorting
Problem
#436
Reading time
2 min

The problem

You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized.

Example

Input
intervals = [[1,2]]
Output
[-1]
Explanation
There is only one interval in the collection, so it outputs -1.

Python solution

Python
class Solution:
    def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
        n = len(intervals)
        ans = [-1] * n
        arr = sorted((st, i) for i, (st, _) in enumerate(intervals))
        for i, (_, ed) in enumerate(intervals):
            j = bisect_left(arr, (ed, -inf))
            if j < n:
                ans[i] = arr[j][1]
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 436. Find Right Interval is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 436. Find Right Interval?
LeetCode 436. Find Right Interval is rated Medium on LeetCode.
What is the time complexity of LeetCode 436. Find Right Interval?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 436. Find Right Interval?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 436. Find Right Interval cover?
LeetCode 436. Find Right Interval is tagged Array, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview