Longest Increasing Subsequence — LeetCode 300 Python Solution

MediumArrayBinary SearchDynamic Programming
Problem
#300
Reading time
2 min

The problem

Given an integer array nums, return the length of the longest strictly increasing subsequence.

Example

Input
nums = [10,9,2,5,3,7,101,18]
Output
4
Explanation
The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Python solution

Python
class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        f = [1] * n
        for i in range(1, n):
            for j in range(i):
                if nums[j] < nums[i]:
                    f[i] = max(f[i], f[j] + 1)
        return max(f)

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 300. Longest Increasing Subsequence is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 300. Longest Increasing Subsequence?
LeetCode 300. Longest Increasing Subsequence is rated Medium on LeetCode.
What topics does LeetCode 300. Longest Increasing Subsequence cover?
LeetCode 300. Longest Increasing Subsequence is tagged Array, Binary Search and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview