Skip to content

Longest Increasing Subsequence (LIS) ​

The Longest Increasing Subsequence (LIS) problem asks you to pick some elements of an array while keeping their order, and find the longest subsequence whose values keep getting larger.

At a Glance ​

Longest increasing subsequence: the longest subsequence that is increasing

  • Subsequence: a sequence picked out by skipping some elements while keeping the original order. The picked elements do not need to be adjacent.
  • Increasing: each value must be larger than the one before it. (This article uses "strictly increasing," which does not allow equal values.)

As an analogy, imagine a line of people where you want to keep only some of them so that their heights increase from front to back. The question is how many people you can keep at most. You cannot swap positions; you can only remove people.

[7, 2, 3, 8, 4, 5] → In this array, [2, 3, 4, 5] is the LIS, so the answer is 4.

[2, 3, 8] is also an increasing subsequence, but with length 3 it is not the longest.

Implementation Methods (Time Complexity) ​

  1. DP: O(N^2)
  2. Lower Bound (binary search): O(N log N)

How It Works ​

DP Approach ​

Using dynamic programming, fill in "dp[i] = the length of the longest increasing subsequence ending at arr[i]."

  1. Start every dp[i] at 1. (The element by itself already has length 1.)
  2. Look at every j before i. If arr[j] < arr[i], arr[i] can be appended to the subsequence ending at arr[j]. The length then becomes dp[j] + 1.
  3. Set dp[i] to the largest of these values.
  4. At the end, the maximum value in all of dp is the answer.

arr = [7, 2, 3, 8, 4, 5]

iarr[i]Earlier values it can be appended todp[i]
07None1
12None1
232 (dp=1)2
387 (dp=1), 2 (dp=1), 3 (dp=2)3
442 (dp=1), 3 (dp=2)3
552 (dp=1), 3 (dp=2), 4 (dp=3)4

dp = [1, 1, 2, 3, 3, 4] → maximum 4.

The original source's code starts dp at 0, so the stored values are [0, 0, 1, 2, 2, 3], and it returns "the maximum value stored in the dp array + 1" as the answer. Every cell is just 1 smaller; it is the same method.

Lower Bound Approach ​

But what if the problem cannot be solved in N^2? (For example, if the array can have up to 100,000 elements, that is 100,000 × 100,000 = 10 billion comparisons.)

In that case, you need an LIS implementation that uses Lower Bound. Lower Bound means using binary search to find the first position in a sorted array whose value is greater than or equal to x.

We maintain tails[k] = "the smallest ending value among increasing subsequences of length k+1." The smaller the ending value, the more values can be appended after it, so smaller is better. tails is always in ascending order, which makes binary search possible.

  1. Look at each value x one by one.
  2. Find the lower bound position of x in tails.
  3. If the position is the end of tails, x is larger than every ending value, so append it and extend the subsequence by one.
  4. Otherwise, replace the ending value at that position with the smaller x. (We found a subsequence of the same length with a smaller ending value.)
  5. When finished, the length of tails is the answer.
xLower bound positiontailsExplanation
70[7]Empty, so append
20[2]Replace 7 with the smaller 2
31[2, 3]At the end, so append
82[2, 3, 8]At the end, so append
42[2, 3, 4]Replace 8 with 4
53[2, 3, 4, 5]At the end, so append

The length of tails, 4, is the answer.

The animation below shows the same idea using candidate subsequences for each length. As values are read one at a time, only one "increasing subsequence with the smallest ending value" is kept for each length, and candidates of the same length with a larger ending value are removed (Inactive). Collecting just the ending value of each row gives the tails above.

Reading the sequence and keeping, for each length, only the increasing subsequence with the smallest ending value to find the LIS length

Image source: Wikimedia Commons (CC BY-SA 4.0, Shiyu Ji)

Note: tails is only a tool for finding the length and may not be the actual LIS itself. For example, with [3, 4, 1], tails becomes [1, 4], but 1 comes after 4, so it is not a real subsequence. (The actual LIS is [3, 4].)

Python Code ​

python
from bisect import bisect_left


# 1. DP approach: O(N^2)
def lis_dp(arr):
    if not arr:
        return 0
    n = len(arr)
    dp = [1] * n                       # dp[i] = LIS length ending at arr[i] (1 even if it is alone)
    for i in range(1, n):
        for j in range(i - 1, -1, -1):
            if arr[i] > arr[j]:        # 2. If it can be appended after a smaller earlier value
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)                     # 3. The longest among them


# 4. Binary search (Lower Bound) approach: O(N log N)
def lis_lower_bound(arr):
    tails = []                         # tails[k] = smallest ending value of an increasing subsequence of length k+1
    for x in arr:
        pos = bisect_left(tails, x)    # 5. First position with a value >= x (lower bound)
        if pos == len(tails):
            tails.append(x)            # 6. If larger than every ending value, extend the subsequence by one
        else:
            tails[pos] = x             # 7. Otherwise, replace the ending value there with the smaller x
    return len(tails)


arr = [7, 2, 3, 8, 4, 5]
print(lis_dp(arr))            # Output: 4
print(lis_lower_bound(arr))   # Output: 4
  1. The same nested loop as the original source. Since dp starts at 1, there is no need to add 1 at the end. For an empty array it returns 0.
  2. Appending arr[i] after the subsequence ending at arr[j] gives length dp[j] + 1, so compare it with the value found so far and keep the longer one.
  3. Since we do not know where the LIS ends, the maximum of all of dp is the answer.
  4. The Lower Bound approach. tails is always kept in ascending order.
  5. bisect_left is the lower bound function in Python's standard library.
  6. If x is the largest, it can be appended after the longest subsequence, so the length grows by 1.
  7. Otherwise, lower the ending value of the subsequence of that length to x, making it easier for later values to be appended.

Recovering the Actual Subsequence ​

If you need the LIS itself and not just its length, record "which element it was appended after" in the DP approach, then follow those records backward. (Supplementary content not in the original source.)

python
def lis_with_path(arr):
    n = len(arr)
    if n == 0:
        return []
    dp = [1] * n
    prev = [-1] * n                    # 1. prev[i] = position of the element that comes right before arr[i]
    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
    i = dp.index(max(dp))              # 2. Start from the position where the longest subsequence ends
    path = []
    while i != -1:                     # 3. Follow prev backward and collect the values
        path.append(arr[i])
        i = prev[i]
    return path[::-1]


print(lis_with_path([7, 2, 3, 8, 4, 5]))  # Output: [2, 3, 4, 5]
  1. Each time dp[i] increases, record "which j it was appended after" in prev[i]. -1 means "nothing comes before it."
  2. The position with the greatest length is the last element of the LIS.
  3. Following prev from the end collects the subsequence in reverse, so it is reversed at the end.

Time and Space Complexity ​

MethodBestAverageWorstExtra space
DPO(N^2)O(N^2)O(N^2)O(N)
Lower BoundO(N)O(N log N)O(N log N)O(N)
  • The DP approach compares every (i, j) pair regardless of the values, so it is always O(N^2).
  • The Lower Bound approach performs an O(log N) binary search for each of the N elements, so it is O(N log N). If the array only keeps decreasing, tails stays at length 1 and each search ends immediately, so the best case is O(N).
  • When N = 100,000, N^2 is 10 billion while N log N is about 1.7 million, a huge difference. For the notation, see the time complexity article.

Where It Is Used ​

  • Baekjoon 11053 "Longest Increasing Subsequence": N is small, so the DP approach is enough.
  • Baekjoon 12015 "Longest Increasing Subsequence 2": N is large, so the Lower Bound approach is required.
  • Baekjoon 2565 "Electric Wires": sort by the pole number on one side, then find the LIS of the numbers on the other side to get "the maximum number of wires that can be kept without crossing."
  • To find a "non-decreasing subsequence" that allows equal values, use bisect_right instead of bisect_left, and in DP use >= instead of >.

Summary ​

ConceptPlain-language summary
LISThe longest line that keeps getting larger when picked in order
SubsequenceA sequence picked by skipping elements while keeping their positions in order
DP approachCompute "the longest line ending here" for every position from the front, O(N^2)
Lower Bound approachRemember only the smallest ending value for each length and update it with binary search, O(N log N)
tails arrayOnly a tool for counting the length; it may differ from the actual LIS