Longest Increasing Subsequence — LeetCode 300 Python Solution
- Problem
- #300
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.