Python 0436.py
class Solution {
public:
vector<int> findRightInterval(vector<vector<int>>& intervals) {
map<int, int> sorted;
for (int i = 0; i < intervals.size(); i++)
{
auto start = intervals[i][0];
sorted[start] = i;
}
vector<int> result;
result.reserve(intervals.size());
for (auto& i : intervals)
{
auto start = i[0];
auto end = i[1];
auto pos = sorted.lower_bound(end);
if (pos == sorted.end())
result.push_back(-1);
else
result.push_back(pos->second);
}
return result;
}
};
Difficulty
and has an acceptance rate of about 56% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that, for each interval in a collection, determines the index of the interval whose start point is the smallest value that is not less than the current interval’s end point. If such an interval does not exist, the method records -1. The result is returned as a vector whose length matches the input size, preserving the original order of intervals.
Data Preparation
The first phase constructs an ordered associative container that maps each interval’s start value to its original position. By iterating over the input vector and inserting (start, index) pairs into a map, the code creates a structure that automatically keeps the keys sorted.
map<int, int> sorted;
for (int i = 0; i < intervals.size(); i++)
{
auto start = intervals[i][0];
sorted[start] = i;
}
Because map maintains a strict weak ordering of its keys, later look-ups can efficiently locate the smallest start that satisfies a given bound.
Query Phase
The second phase walks through the original intervals, extracts the start and end of each, and uses the previously built map to locate the right interval. The lower_bound operation on the map returns an iterator to the first element whose key is not less than the queried end value.
vector<int> result;
result.reserve(intervals.size());
for (auto& i : intervals)
{
auto start = i[0];
auto end = i[1];
auto pos = sorted.lower_bound(end);
if (pos == sorted.end())
result.push_back(-1);
else
result.push_back(pos->second);
}
return result;
If lower_bound reaches the end of the map, it indicates that no interval starts at or after the current end, and -1 is recorded. Otherwise, the index stored in the map entry is appended to the result.
Edge Cases Handled
When an interval’s end exceeds all start values in the collection, the lower_bound call yields sorted.end(). The conditional branch captures this situation and inserts -1, ensuring that the output correctly reflects the absence of a suitable right interval.
If multiple intervals share the same start value, the map stores the last index encountered for that start because later insertions overwrite earlier ones. This deterministic choice guarantees that the method always returns a single, well-defined index for any given start value.
The algorithm also gracefully handles an empty input vector: the initial loop does not execute, the result vector remains empty, and the method returns an empty vector without error.
Performance Optimizations
The code reserves space in the result vector equal to the number of intervals before populating it. This pre-allocation eliminates repeated reallocations and copies as elements are appended, yielding a smoother memory usage pattern.
Using a map provides logarithmic-time search for the lower bound of each interval’s end, which is more efficient than a linear scan over unsorted starts.
The range-based for loop iterates by reference (auto& i), avoiding unnecessary copies of the inner vectors while still allowing direct access to their elements.
Type deduction with auto reduces verbosity and lets the compiler infer the most appropriate types, potentially enabling better register allocation and inlining.
Overall, the combination of ordered storage, pre-allocation, and reference-based iteration contributes to a solution that scales well with the size of the input while keeping the runtime overhead minimal.
ELI5 - Simplified Explanation
Imagine a row of colorful bridges. Some bridges start at a certain distance and end a little bit further away. This code is like playing a game where you stand at the end of one bridge and try to find the very next bridge that starts at the same spot or even further down the path.
First, the computer gathers all the starting points of the bridges and puts them into a special list that is kept organized from smallest to largest, just like sorting your blocks by size. This makes it really fast to peek at them later.
Next, the computer looks at each bridge one by one. It finds where the bridge ends and then looks through that organized list to see if there is another bridge that begins right there or a little bit further ahead. If it finds one, it writes down which bridge that is. If it reaches the very end of the line and realizes there are no more bridges left to jump onto, it writes down a special number to say that nothing was found. It keeps doing this until it has checked every single bridge in the whole set.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 352: Data Stream as Disjoint Intervals
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality