Back to Home

Longest Increasing Subsequence

A dynamic programming problem to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

Visualization

Step 1 / 10
Speed:

Details

Analogy

Imagine a line of people of different heights. You want to pick a smaller group of people from this line, keeping them in their original order, such that they are arranged from shortest to tallest. The goal is to find the largest possible group you can form this way.

Purpose

To find the longest subsequence where elements are in strictly increasing order. The elements do not have to be contiguous.

Use Cases

Used in data analysis, bioinformatics (analyzing gene sequences), and string matching algorithms.

Algorithm Steps

Line 1
1
create dp array of size n, fill with 1
2
for i = 1 to n-1:
3
for j = 0 to i-1:
4
if arr[i] > arr[j]:
5
dp[i] = max(dp[i], dp[j] + 1)
6
return max(dp)
Current
Executed
Pending

Explanation

What's Happening?

Step 1/10

Initial array. We will build a DP array representing the length of the LIS ending at each index.

Updates with each step • Clickfor full view

Code Implementation

def length_of_lis(nums):
    if not nums:
        return 0
    dp = [1] * len(nums)
    for i in range(1, len(nums)):
        for j in range(i):
            if nums[i] > nums[j]:
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)
Longest Increasing Subsequence - Interactive Visualization | AlgoViz | AlgoViz