Longest Increasing Subsequence - Problem

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

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
💡 Note: The longest increasing subsequence is [2,3,7,101] or [2,3,7,18] or [2,5,7,101] or [2,5,7,18], all with length 4.
Example 2 — All Decreasing
$ Input: nums = [0,1,0,3,2,3]
Output: 4
💡 Note: The longest increasing subsequence is [0,1,2,3] with length 4.
Example 3 — All Same Elements
$ Input: nums = [7,7,7,7,7,7,7]
Output: 1
💡 Note: Since all elements are the same, the longest strictly increasing subsequence has length 1.

Constraints

  • 1 ≤ nums.length ≤ 2500
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Longest Increasing Subsequence INPUT nums array: 10 i=0 9 i=1 2 i=2 5 i=3 3 i=4 7 i=5 101 i=6 18 i=7 = Part of LIS One Valid LIS: [2, 5, 7, 101] 2 < 5 < 7 < 101 Strictly increasing! Length = 4 ALGORITHM STEPS 1 Initialize DP Array dp[i] = 1 for all i (each element is LIS of 1) 2 Compare Pairs For each i, check all j < i If nums[j] < nums[i] 3 Update DP dp[i] = max(dp[i], dp[j]+1) Extend previous LIS 4 Find Maximum Return max(dp[]) Longest among all Final DP Array: 1 1 1 2 2 3 4 4 dp values for each index FINAL RESULT Maximum DP value found: 4 Length of LIS = 4 One possible LIS: 2 < 5 < 7 < 101 Output: 4 OK - Correct Answer! Key Insight: Dynamic Programming builds LIS incrementally. For each element, we check all previous elements to find the longest increasing subsequence that can be extended. Time: O(n^2), Space: O(n). Can be optimized to O(n log n) using binary search with patience sorting technique. TutorialsPoint - Longest Increasing Subsequence | Optimal Solution (DP)
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
87.5K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen