#436

Find Right Interval

Medium
ArrayBinary SearchSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the intervals based on their start times and using binary search, we can efficiently find the right interval for each interval in O(n log n) time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a list of tuples containing each interval's start and its original index.
  2. 2Step 2: Sort this list based on the start times of the intervals.
  3. 3Step 3: For each interval, use binary search to find the smallest start time that is greater than or equal to the end time of the current interval.
  4. 4Step 4: Store the corresponding original index in the result array.
  5. 5Step 5: Return the result array.
solution.py16 lines
1def findRightInterval(intervals):
2    indexed_intervals = [(start, i) for i, (start, end) in enumerate(intervals)]
3    indexed_intervals.sort()
4    result = [-1] * len(intervals)
5    for start, i in indexed_intervals:
6        end = intervals[i][1]
7        left, right = 0, len(intervals)
8        while left < right:
9            mid = (left + right) // 2
10            if intervals[mid][0] < end:
11                left = mid + 1
12            else:
13                right = mid
14        if left < len(intervals):
15            result[i] = indexed_intervals[left][1]
16    return result

Complexity note: The time complexity is O(n log n) due to the sorting step, while the binary search for each interval takes O(log n), making it efficient for larger datasets. The space complexity is O(n) because we store the indexed intervals.

  • 1Sorting intervals helps in efficiently finding the right interval using binary search.
  • 2Unique start times allow for a straightforward mapping of intervals to their indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.