MediumNo. 0300
Longest Increasing Subsequence — LeetCode 300 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search, Dynamic Programming
- On study lists
- Blind 75, NeetCode 150 and Top Interview 150
- 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
- Time
- O(log n) or O(n log n)
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2407 | Longest Increasing Subsequence II | Hard |
| 0354 | Russian Doll Envelopes | Hard |
| 0410 | Split Array Largest Sum | Hard |
| 0902 | Numbers At Most N Given Digit Set | Hard |
| 1187 | Make Array Strictly Increasing | Hard |
| 1235 | Maximum Profit in Job Scheduling | Hard |
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.