KatInterview

436. Find Right Interval

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find, for each interval i, a "right interval" j. A right interval j must satisfy two conditions: its start time start_j is greater than or equal to interval i's end time end_i, and among all such valid intervals, start_j is minimized. We need to return the original index of this interval j. If no such interval exists, we return -1.

Solution

Find Right Interval in Python

import bisect

class Solution:
    def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
        n = len(intervals)
        
        # Create a list of tuples (start_time, original_index) to track indices after sorting.
        start_info = []
        for i in range(n):
            start_info.append((intervals[i][0], i))
        
        # Sort based on start times. Python's sort on tuples works by the first element by default.
        start_info.sort()
        
        result = []
        for i in range(n):
            end_time = intervals[i][1]
            
            # bisect_left finds the insertion point for end_time, which corresponds to the
            # first element that is not less than the target.
            # We search with a tuple (end_time, -1) because bisect works on the sorted list of tuples.
            # The second element of the search key can be any value, as comparison starts with the first element.
            idx = bisect.bisect_left(start_info, (end_time, -float('inf')))
            
            if idx == n:
                # No interval found with start_time >= end_time.
                result.append(-1)
            else:
                # The found interval's original index is start_info[idx][1].
                result.append(start_info[idx][1])
                
        return result

Find Right Interval in Java

class Solution {
    public int[] findRightInterval(int[][] intervals) {
        int n = intervals.length;
        
        // Store pairs of [start_time, original_index] to keep track of indices after sorting.
        int[][] startInfo = new int[n][2];
        for (int i = 0; i < n; i++) {
            startInfo[i][0] = intervals[i][0];
            startInfo[i][1] = i;
        }

        // Sort the pairs based on start times.
        Arrays.sort(startInfo, (a, b) -> Integer.compare(a[0], b[0]));

        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            int endTime = intervals[i][1];
            
            // Binary search to find the smallest start_time >= endTime.
            int low = 0;
            int high = n - 1;
            int foundPos = -1; // -1 indicates not found

            while (low <= high) {
                int mid = low + (high - low) / 2;
                if (startInfo[mid][0] >= endTime) {
                    // This is a potential candidate. Store its position in the sorted array.
                    foundPos = mid;
                    // Try to find a better one (smaller start time) to the left.
                    high = mid - 1;
                } else {
                    // The start time is too small, need to look to the right.
                    low = mid + 1;
                }
            }

            if (foundPos == -1) {
                result[i] = -1;
            } else {
                // The original index is stored at startInfo[foundPos][1].
                result[i] = startInfo[foundPos][1];
            }
        }
        return result;
    }
}

Find Right Interval in C++

class Solution {
public:
    vector<int> findRightInterval(vector<vector<int>>& intervals) {
        int n = intervals.size();
        // Store pairs of (start_time, original_index) to keep track of indices after sorting.
        vector<pair<int, int>> starts;
        for (int i = 0; i < n; ++i) {
            starts.push_back({intervals[i][0], i});
        }

        // Sort the pairs based on start times.
        sort(starts.begin(), starts.end());

        vector<int> result(n);
        for (int i = 0; i < n; ++i) {
            int end_time = intervals[i][1];
            
            // We need to find the smallest start_time >= end_time.
            // This is exactly what lower_bound does.
            // We create a dummy pair {end_time, 0} to search. The second element doesn't matter
            // for the comparison as std::pair compares first elements first.
            auto it = lower_bound(starts.begin(), starts.end(), make_pair(end_time, 0));

            if (it == starts.end()) {
                // No interval found with start_time >= end_time.
                result[i] = -1;
            } else {
                // An interval is found. Its original index is stored in the second part of the pair.
                result[i] = it->second;
            }
        }
        return result;
    }
};

Find Right Interval in TypeScript

function findRightInterval(intervals: number[][]): number[] {
    const n = intervals.length;
    
    // Store objects {start, index} to keep track of indices after sorting.
    const startInfo = intervals.map((interval, index) => ({
        start: interval[0],
        index: index
    }));

    // Sort the objects based on start times.
    startInfo.sort((a, b) => a.start - b.start);

    const result: number[] = new Array(n);
    for (let i = 0; i < n; i++) {
        const endTime = intervals[i][1];

        // Binary search to find the smallest start time >= endTime.
        let low = 0;
        let high = n - 1;
        let foundPos = -1; // -1 indicates not found

        while (low <= high) {
            const mid = Math.floor(low + (high - low) / 2);
            if (startInfo[mid].start >= endTime) {
                // This is a potential candidate. Store its position.
                foundPos = mid;
                // Try to find a better one (smaller start time) to the left.
                high = mid - 1;
            } else {
                // The start time is too small, look to the right.
                low = mid + 1;
            }
        }

        if (foundPos === -1) {
            result[i] = -1;
        } else {
            // The original index is stored in the found object.
            result[i] = startInfo[foundPos].index;
        }
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.