C++ 0300.cpp
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
map<int, int> lengths;
for (auto x : nums)
{
auto maxx = 0;
for (auto i = lengths.begin(); i->first < x && i != lengths.end(); i++)
if (maxx < i->second)
maxx = i->second;
lengths[x] = maxx + 1;
}
auto result = 0;
for (auto l : lengths)
if (result < l.second)
result = l.second;
return result;
}
};
Difficulty
and has an acceptance rate of about 60% (4+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Dynamic Programming
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 computes the length of the longest increasing subsequence (LIS) for a given integer vector. It builds a map that associates each distinct value encountered with the length of the longest increasing subsequence that ends with that value. By iterating through the input once and updating the map based on previously stored lengths, the algorithm derives the final answer without needing a separate dynamic-programming table for every index.
Data Structure Initialization
The algorithm begins by declaring an ordered map from integer keys to integer values. The map, named lengths, will store the best LIS length for each distinct number seen so far.
map<int, int> lengths;
Because the map maintains its keys in sorted order, it enables efficient lookup of all entries whose keys are smaller than the current element.
Main Loop Over Input Elements
For each element x in the input vector, the code searches the map for entries with keys less than x. It tracks the maximum subsequence length among those entries in a temporary variable maxx. The inner loop stops as soon as it reaches a key that is not smaller than x, thanks to the ordered nature of the map.
for (auto x : nums)
{
auto maxx = 0;
for (auto i = lengths.begin(); i->first < x && i != lengths.end(); i++)
if (maxx < i->second)
maxx = i->second;
lengths[x] = maxx + 1;
}
When the inner loop finishes, maxx holds the length of the longest increasing subsequence that can be extended by x. The map entry for x is then set to maxx + 1, representing the new subsequence length that ends with x. If x appears multiple times, the later assignment overwrites the previous one, automatically keeping the best length for that value.
Result Extraction
After processing all input numbers, the algorithm scans the map to find the largest stored subsequence length. This final pass extracts the overall LIS length.
auto result = 0;
for (auto l : lengths)
if (result < l.second)
result = l.second;
return result;
The variable result is updated whenever a larger length is encountered, and its final value is returned as the answer.
Edge Cases Handled
When the input vector is empty, the outer loop never executes, leaving the map empty. The subsequent result extraction loop also never updates result, which remains zero, correctly indicating that the LIS length of an empty sequence is zero.
If the input contains duplicate values, each occurrence updates the map entry for that value. Because the map stores only the greatest length associated with a key, earlier smaller lengths are automatically superseded, ensuring that duplicates do not inflate the result.
For a strictly decreasing sequence, the inner loop never finds a key smaller than the current element, leaving maxx at zero for each iteration. Consequently, each map entry receives a length of one, and the final result correctly reflects that the longest increasing subsequence consists of a single element.
When all elements are equal, the map ends up with a single entry whose length grows to one, as the inner loop condition i->first < x never holds for equal keys. The algorithm therefore returns one, which is the correct LIS length for a constant sequence.
Performance Optimizations Observed
The use of an ordered map eliminates the need for a full scan of all previously processed elements. By iterating only until a key no longer satisfies the < x condition, the inner loop processes a prefix of the map rather than the entire structure. This selective traversal reduces the amount of work when many larger keys have already been stored.
Storing only the best length for each distinct value avoids redundant storage of multiple subsequence lengths that would otherwise be associated with the same number. Overwrites of map entries guarantee that the map remains compact, containing at most one entry per unique value.
The final pass that determines the maximum length operates on the map’s entries directly, without recomputing any intermediate values. This straightforward aggregation leverages the already computed lengths, completing the algorithm with minimal additional overhead.
ELI5 - Simplified Explanation
Imagine a long line of numbered building blocks sitting on the floor. The goal is to find the longest path you can make by picking blocks one by one, but you must always pick blocks that have bigger numbers than the one you picked just before.
To do this, the computer looks at each block in your line and keeps a special notebook. In this notebook, it writes down the best possible path it has found that ends with that specific block.
When the computer looks at a new block, it checks its notebook to see which previous blocks have smaller numbers. It finds the longest path that leads to one of those smaller blocks and adds the new block to the very end of that path. This makes the path one block longer. The computer writes this new, longer size in the notebook next to the current block's number.
Once every block has been checked, the notebook contains all the different ways to build paths throughout the line. The computer then looks through every entry in the notebook to see which path is the longest overall, and that big number is the answer to the puzzle.
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 | Rust | Go | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| ruoru | Rust | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| ruoru | Rust | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 334: Increasing Triplet Subsequence
- problem 354: Russian Doll Envelopes
- problem 673: Number of Longest Increasing Subsequence
- problem 1964: Find the Longest Valid Obstacle Course at Each Position
- problem 2370: Longest Ideal Subsequence
- problem 3231: Minimum Number of Increasing Subsequence to Be Removed
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 436: Find Right Interval
- 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