Longest Increasing Subsequence (LIS) Algorithm
The Longest Increasing Subsequence problem involves finding the longest subsequence in a given array of integers where the elements are in strictly increasing order. A subsequence maintains the same relative order as the original array but doesn't have to be contiguous.
Approach
- Use dynamic programming to compute the LIS in O(n²) time and O(n) space.
dp[i]: Length of the LIS ending at index i.
prev[i]: Index of the previous element in the LIS ending at i (for reconstruction).
- Find the index with the maximum
dp value, then backtrack using prev to build the subsequence.
- This returns one possible LIS (there may be multiple).
Pseudocode
function longestIncreasingSubsequence(arr):
n = length(arr)
if n == 0:
return []
dp = array of size n, initialized to 1
prev = array of size n, initialized to -1
for i from 1 to n-1:
for j from 0 to i-1:
if arr[j] < arr[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
prev[i] = j
max_len = maximum value in dp
end_idx = index of maximum value in dp
# Reconstruct the subsequence
lis = empty list
current = end_idx
while current != -1:
prepend arr[current] to lis // or append and reverse later
current = prev[current]
return lis
Python Implementation
def longest_increasing_subsequence(arr):
n = len(arr)
if n == 0:
return []
dp = [1] * n
prev = [-1] * n
max_len = 1
end_idx = 0
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
prev[i] = j
if dp[i] > max_len:
max_len = dp[i]
end_idx = i
# Reconstruct LIS
lis = []
current = end_idx
while current != -1:
lis.append(arr[current])
current = prev[current]
return lis[::-1] # Reverse to get correct order
# Example usage
arr1 = [10, 9, 2, 5, 3, 7, 101, 18]
print(longest_increasing_subsequence(arr1)) # Output: [2, 3, 7, 101] (length 4)
arr2 = [7, 7, 7, 7]
print(longest_increasing_subsequence(arr2)) # Output: [7] (length 1, strict increasing)
arr3 = [1, 3, 2, 4]
print(longest_increasing_subsequence(arr3)) # Output: [1, 3, 4] or [1, 2, 4]
Complexity
- Time: O(n²) due to nested loops.
- Space: O(n) for
dp and prev.
Optimized for Length Only (O(n log n))
If you only need the length (not the subsequence), use binary search:
import bisect
def length_of_lis(arr):
if not arr:
return 0
tails = []
for num in arr:
if not tails or num > tails[-1]:
tails.append(num)
else:
tails[bisect.bisect_left(tails, num)] = num
return len(tails)
- Example:
length_of_lis([10, 9, 2, 5, 3, 7, 101, 18]) → 4
- Reconstructing the full subsequence from this requires additional bookkeeping (e.g., tracking indices).
This covers the standard, efficient, and reconstructible solution! If you need variations (e.g., non-strict increasing, weighted), let me know.