Tutorialspoint
Problem
Solution
Submissions

Find the Longest Increasing Subsequence

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Write a Python function that finds the length of the longest increasing subsequence in a given list of integers. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1
  • Input: [10, 22, 9, 33, 21, 50, 41, 60, 80]
  • Output: 6
  • Explanation:
    • Step 1: Initialize an array dp[n] where dp[i] represents the length of LIS ending at index i.
    • Step 2: For each element, compare with all previous elements.
    • Step 3: If the current element is greater than a previous element, update dp[i].
    • Step 4: The longest increasing subsequence is [10, 22, 33, 50, 60, 80] with length 6.
Example 2
  • Input: [3, 10, 2, 1, 20]
  • Output: 3
  • Explanation:
    • Step 1: Initialize dp array with all values as 1.
    • Step 2: For each element at position i, check all elements at positions j < i.
    • Step 3: If nums[i] > nums[j], update dp[i] = max(dp[i], dp[j] + 1).
    • Step 4: The longest increasing subsequence is [3, 10, 20] with length 3.
Constraints
  • 1 ≤ len(nums) ≤ 2500
  • -10^4 ≤ nums[i] ≤ 10^4
  • Time Complexity: O(n²), where n is the length of the input list
  • Space Complexity: O(n)
ListDynamic Programming Tech MahindraCapgemini
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming where dp[i] represents the length of the LIS ending at index i
  • For each position, check all previous positions to find the longest subsequence that can be extended
  • The maximum value in the dp array will be the length of the LIS
  • Handle empty list as a special case (return 0)

Steps to solve by this approach:

 Step 1: Create a DP array where dp[i] represents the length of LIS ending at index i.
 Step 2: Initialize all dp values to 1 (minimum LIS length).
 Step 3: For each position i, consider all previous positions j < i.
 Step 4: If nums[i] > nums[j], update dp[i] = max(dp[i], dp[j] + 1).
 Step 5: Keep track of the maximum value in the dp array.
 Step 6: Return the maximum LIS length found.

Submitted Code :