Print Longest Increasing Subsequence
Pattern: LIS family
To print an LIS, use the O(n²) DP and also store prev[i], the index before i in the best run ending at i. Start at the index with the longest run and follow prev back.
The problem
Return one longest strictly increasing subsequence of arr (as a list of values). Any longest one is accepted: the tests check its length and that it is an increasing subsequence of arr.
Think first
- What does the length DP lose that you need now?
- What extra value is stored per index?
- In what order do you collect the values?
Hints
Brute force, and why it fails
Generate every subsequence and keep the longest increasing one: 2ⁿ.
The key insight
Storing the choice made at each index lets you rebuild the answer in O(n) after the DP.
Dry run
[10, 9, 2, 5, 3, 7, 101, 18]. len: 1 1 1 2 2 3 4 4.
Step 1 of 2
The plan
len[i] = 1 + max len[j] for j < i, a[j] < a[i]; prev[i] = that j
end = argmax len
follow prev from end; reverse
Complexity
- Time
O(n²)- Space
O(n)
Every pair (i, j).
Edge cases
- One value.
- All equal: one value.
- Several longest answers.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> longestIncreasingSubsequence(int[] arr) {
int n = arr.length;
int[] len = new int[n], prev = new int[n]; // len[i]: the longest run ending at i; prev[i]: the index before i in it
int end = 0;
for (int i = 0; i < n; i++) {
len[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++)
if (arr[j] < arr[i] && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; }
if (len[i] > len[end]) end = i;
}
LinkedList<Integer> out = new LinkedList<>();
for (int i = end; i != -1; i = prev[i]) out.addFirst(arr[i]); // follow the links back from the best end
return out;
}
}C++
class Solution {
public:
vector<int> longestIncreasingSubsequence(vector<int>& arr) {
int n = static_cast<int>(arr.size());
vector<int> len(n, 1), prev(n, -1); // len[i]: the longest run ending at i; prev[i]: the index before i in it
int end = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++)
if (arr[j] < arr[i] && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; }
if (len[i] > len[end]) end = i;
}
vector<int> out;
for (int i = end; i != -1; i = prev[i]) out.push_back(arr[i]); // follow the links back from the best end
reverse(out.begin(), out.end());
return out;
}
};Python
class Solution:
def longestIncreasingSubsequence(self, arr: list[int]) -> list[int]:
n = len(arr)
length, prev = [1] * n, [-1] * n # the longest run ending at i, and the index before i in it
for i in range(n):
for j in range(i):
if arr[j] < arr[i] and length[j] + 1 > length[i]:
length[i], prev[i] = length[j] + 1, j
i, out = max(range(n), key=lambda k: (length[k], -k)), []
while i != -1: # follow the links back from the best end
out.append(arr[i])
i = prev[i]
return out[::-1]Common mistakes
- Rebuilding from the O(n log n) tails array.
- Forgetting to reverse.