Problem 300

Abstract / Summary

Find the length of the longest strictly increasing subsequence in a given list of numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
22 lines | 550 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (4+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.30 | σ = 1.74

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
56 links | 41 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Longest Increasing Subsequence - Dynamic Programming - Leetcode 300'
NeetCode 19 mins
Longest Increasing Subsequence - Dynamic Programming - Leetcode 300
YouTube video 'Longest Increasing Subsequence | Dynamic Programming'
Pepcoding 27 mins
Longest Increasing Subsequence | Dynamic Programming
YouTube video 'Longest Increasing Subsequence - Leetcode 300 - Dynamic Programming (Python)'
Greg Hogg 9 mins
Longest Increasing Subsequence - Leetcode 300 - Dynamic Programming (Python)
YouTube video 'Longest Increasing Subsequence | Patience Sorting | DP Concepts & Qns-17 | Leetcode 300'
codestorywithMIK 21 mins
Longest Increasing Subsequence | Patience Sorting | DP Concepts & Qns-17 | Leetcode 300
YouTube video 'Patience Sort | Longest Increasing Subsequence in O(n log n) Time complexity | Coders Camp'
Coders Camp 10 mins
Patience Sort | Longest Increasing Subsequence in O(n log n) Time complexity | Coders Camp
YouTube video 'Longest Increasing Subsequence in O(nlogn) | LeetCode | Algorithm Explanation by alGOds!!'
alGOds 22 mins
Longest Increasing Subsequence in O(nlogn) | LeetCode | Algorithm Explanation by alGOds!!
YouTube video '✅ Longest Increasing Subsequence - LeetCode 300 - Binary Search - Arrays - Explained'
Leet Logics 7 mins
✅ Longest Increasing Subsequence - LeetCode 300 - Binary Search - Arrays - Explained
YouTube video 'LeetCode 300. Longest Increasing Subsequence - O(n log n)'
Kacy Codes 11 mins
LeetCode 300. Longest Increasing Subsequence - O(n log n)
YouTube video '[Java] Leetcode 300. Longest Increasing Subsequence [DP Subsequence #1]'
Eric Programming 34 mins
[Java] Leetcode 300. Longest Increasing Subsequence [DP Subsequence #1]
YouTube video 'Longest Increasing Subsequence |  Leetcode 300 | Live coding session | O(nlogn) and O(n2) solution'
Coding Decoded 19 mins
Longest Increasing Subsequence | Leetcode 300 | Live coding session | O(nlogn) and O(n2) solution
YouTube video 'Longest Increasing Subsequence - LeetCode 300 - Python - O(nlog(n))'
Deepti Talesra 17 mins
Longest Increasing Subsequence - LeetCode 300 - Python - O(nlog(n))
YouTube video 'Longest Increasing Subsequence | Leetcode 300 | Brute + Optimal | C++ | Python | DP'
Ayushi Sharma 22 mins
Longest Increasing Subsequence | Leetcode 300 | Brute + Optimal | C++ | Python | DP
YouTube video 'Longest Increasing Subsequence - LeetCode 300 -  Binary Search - Coding Interview'
One Code Man 9 mins
Longest Increasing Subsequence - LeetCode 300 - Binary Search - Coding Interview
YouTube video 'Longest Increasing Subsequence - LeetCode 300 - JavaScript'
AlgoJS 7 mins
Longest Increasing Subsequence - LeetCode 300 - JavaScript
YouTube video 'Longest Increasing Subsequence | Leetcode - 300'
Algorithms Made Easy 32 mins
Longest Increasing Subsequence | Leetcode - 300
YouTube video 'Longest Increasing Subsequence Dynamic Programming'
Knowledge Center 18 mins
Longest Increasing Subsequence Dynamic Programming
YouTube video 'Patience Sort | Longest Increasing Subsequence | O(nlogn) time |  Stable Sort | Leetcode 300'
Coding Decoded 12 mins
Patience Sort | Longest Increasing Subsequence | O(nlogn) time | Stable Sort | Leetcode 300
YouTube video 'Leetcode | 300. Longest Increasing Subsequence | Medium | Java Solution'
Developer Docs 12 mins
Leetcode | 300. Longest Increasing Subsequence | Medium | Java Solution
YouTube video 'Longest Increasing Subsequence | Binary Search | Leetcode 300'
Knowledge Center 25 mins
Longest Increasing Subsequence | Binary Search | Leetcode 300
YouTube video 'Daily Leetcode #1375: Jan 05, 2024 - 300. Longest Increasing Subsequence'
Programming Live with Larry 18 mins
Daily Leetcode #1375: Jan 05, 2024 - 300. Longest Increasing Subsequence
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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