Longest Increasing Subsequence

How to find the longest increasing subsequence with an O(n²) table or an O(n log n) binary search, its variants, and what interviewers ask about it.

18 minLesson 6 of 6
On this page
  1. Defining the state: the best sequence that ends at each position
  2. The O(n²) table in code
  3. The O(n log n) method: keep the smallest ending for each length
  4. Variants and when LIS does not apply
  5. Pitfalls and nuances
  6. In the interview
  7. What to practise next

The longest increasing subsequence (LIS) of a list is the longest sequence of values, taken in their original order and not necessarily next to each other, in which each value is larger than the one before it. You use it when a problem asks how many items you can keep, or how few you must remove, so that what remains is in increasing order.

Take eight books on a shelf with heights 5, 2, 8, 6, 3, 6, 9, 7. The longest increasing subsequence has length 4, for example 2, 3, 6, 9. If you want the remaining books to rise in height from left to right, you keep those 4 and remove the other 4, which is the fewest removals possible. The brute-force approach of checking every subset takes exponential time, while dynamic programming solves the problem in O(n²) and a binary search trick in O(n log n).

5 2 8 6 3 6 9 7 0 1 2 3 4 5 6 7
The highlighted books, with heights 2, 3, 6 and 9, rise from left to right, and no five books on the shelf do.

Defining the state: the best sequence that ends at each position

The usual 1D DP choice is to let best[i] be the answer for the first i values. That does not work here, because to decide whether value i can extend a sequence you need to know the last value of that sequence, and best[i] does not tell you.

The fix is to define each cell as the longest increasing subsequence that ends exactly at position i. Then the last value is known: it is h[i], the height at position i.

  1. State. len[i] is the length of the longest increasing subsequence that ends at index i.
  2. Recurrence. len[i] = 1 + max(len[j]) over all earlier indexes j < i with h[j] < h[i].
  3. Base case. If no earlier value is smaller, len[i] = 1, because the value alone is a sequence.
  4. Order. Each cell reads cells to its left, so fill the table from left to right.
  5. Answer. The largest value in len, because the longest sequence can end at any position.
Fill len[i] for heights 5, 2, 8, 6, 3, 6, 9, 7Use the arrows or ← → keys
for i from 0 to n - 1:  len[i] = 1                     # just h[i] on its own  for j from 0 to i - 1:    if h[j] < h[i]:      len[i] = max(len[i], len[j] + 1)return max(len)
  1. heights
    05i
    12
    28
    36
    43
    56
    69
    77
    len
    01i
    1
    2
    3
    4
    5
    6
    7

    1The first book has height 5 and nothing comes before it, so len[0] = 1.

  2. heights
    05
    12i
    28
    36
    43
    56
    69
    77
    len
    01
    11i
    2
    3
    4
    5
    6
    7

    2The book with height 2 has no shorter book before it, so len[1] = 1.

  3. heights
    05
    12
    28i
    36
    43
    56
    69
    77
    len
    01
    11
    22i
    3
    4
    5
    6
    7

    3Both earlier books are shorter than 8 and each has length 1, so len[2] = 1 + 1 = 2.

  4. heights
    05
    12
    28
    36i
    43
    56
    69
    77
    len
    01
    11
    22
    32i
    4
    5
    6
    7

    4The books 5 and 2 are shorter than 6, and the best length among them is 1, so len[3] = 1 + 1 = 2.

  5. heights
    05
    12
    28
    36
    43i
    56
    69
    77
    len
    01
    11
    22
    32
    42i
    5
    6
    7

    5Only the book 2 is shorter than 3, and its length is 1, so len[4] = 1 + 1 = 2. This ties with the 8 and the 6 but ends at a lower height, which matters for the faster method below.

  6. heights
    05
    12
    28
    36
    43
    56i
    69
    77
    len
    01
    11
    22
    32
    42
    53i
    6
    7

    6The books 5, 2 and 3 are shorter than this 6, and the best length among them is 2, so len[5] = 2 + 1 = 3.

  7. heights
    05
    12
    28
    36
    43
    56
    69i
    77
    len
    01
    11
    22
    32
    42
    53
    64i
    7

    7Every earlier book is shorter than 9, and the best length among them is 3, so len[6] = 3 + 1 = 4.

  8. heights
    05
    12
    28
    36
    43
    56
    69
    77i
    len
    01
    11
    22
    32
    42
    53
    64
    74i

    8The books 5, 2, 6, 3 and 6 are shorter than 7, and the best length among them is 3, so len[7] = 3 + 1 = 4.

  9. heights
    05
    12
    28
    36
    43
    56
    69
    77
    len
    01
    11
    22
    32
    42
    53
    64
    74
    answer
    4

    9The answer is the largest value in len, which is 4 at index 6. Walking back through shorter books whose length is one less gives 2, 3, 6, 9.

1 / 9

The O(n²) table in code

O(n²): one cell per position
function lisLength(heights) {
  const n = heights.length;
  const len = new Array(n).fill(1); // each value alone has length 1
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < i; j++) {
      if (heights[j] < heights[i]) {
        len[i] = Math.max(len[i], len[j] + 1); // extend the run ending at j
      }
    }
  }
  return len.reduce((a, b) => Math.max(a, b), 0); // best over every end
}
 
lisLength([5, 2, 8, 6, 3, 6, 9, 7]); // 4
def lis_length(heights):
    n = len(heights)
    length = [1] * n  # each value alone has length 1
    for i in range(n):
        for j in range(i):
            if heights[j] < heights[i]:
                length[i] = max(length[i], length[j] + 1)  # extend the run ending at j
    return max(length, default=0)  # best over every end
 
lis_length([5, 2, 8, 6, 3, 6, 9, 7])  # 4

The O(n log n) method: keep the smallest ending for each length

The table compares every pair of values, which is too slow for inputs of tens of thousands of values. The faster method keeps a list tails, where tails[k] is the smallest last value of any increasing subsequence of length k + 1 found so far.

The smallest last value is the useful one to keep. Of two subsequences with the same length, the one that ends lower is easier to extend, because any value that fits after the higher ending also fits after the lower one.

For each new value x, find the first tail that is greater than or equal to x. If there is none, x extends the longest subsequence, so append it. Otherwise replace that tail with x, because a subsequence of that length can now end lower. The list tails always stays sorted, so the search is a binary search, and each value costs about log n steps.

The tails method on the same shelfUse the arrows or ← → keys
tails = []for x in heights:  k = first index with tails[k] >= x   # binary search  if k == len(tails): append x  else: tails[k] = xreturn len(tails)
  1. heights
    05i
    12
    28
    36
    43
    56
    69
    77
    tails
    05

    1The list tails is empty, so 5 becomes the first entry, a sequence of length 1.

  2. heights
    05
    12i
    28
    36
    43
    56
    69
    77
    tails
    02

    2The first tail that is at least 2 is the 5 at index 0, so 2 replaces it. A sequence of length 1 can now end at 2 instead of 5, which leaves more room to grow.

  3. heights
    05
    12
    28i
    36
    43
    56
    69
    77
    tails
    02
    18

    3The value 8 is larger than every tail, so it is appended and the longest length becomes 2.

  4. heights
    05
    12
    28
    36i
    43
    56
    69
    77
    tails
    02
    16

    4The first tail that is at least 6 is 8, so 6 replaces it. Length 2 now ends at 6.

  5. heights
    05
    12
    28
    36
    43i
    56
    69
    77
    tails
    02
    13

    5The first tail that is at least 3 is 6, so 3 replaces it. Length 2 now ends at 3.

  6. heights
    05
    12
    28
    36
    43
    56i
    69
    77
    tails
    02
    13
    26

    6This 6 is larger than every tail, so it is appended and the longest length becomes 3.

  7. heights
    05
    12
    28
    36
    43
    56
    69i
    77
    tails
    02
    13
    26
    39

    7The value 9 is larger than every tail, so it is appended and the longest length becomes 4.

  8. heights
    05
    12
    28
    36
    43
    56
    69
    77i
    tails
    02
    13
    26
    37

    8The first tail that is at least 7 is 9, so 7 replaces it. Length 4 now ends at 7.

  9. heights
    05
    12
    28
    36
    43
    56
    69
    77
    tails
    02
    13
    26
    37
    answer
    4

    9There are four tails, so the answer is 4, the same as the table gave. Each height cost one binary search instead of a scan. Only the length of tails is the answer; its contents are not the sequence itself.

1 / 9
O(n log n) with binary search
function lisLengthFast(heights) {
  const tails = [];
  for (const x of heights) {
    let lo = 0;
    let hi = tails.length; // find the first tail >= x
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = x; // replaces a tail, or appends when lo === tails.length
  }
  return tails.length;
}
 
lisLengthFast([5, 2, 8, 6, 3, 6, 9, 7]); // 4
from bisect import bisect_left
 
def lis_length_fast(heights):
    tails = []
    for x in heights:
        k = bisect_left(tails, x)  # first tail >= x
        if k == len(tails):
            tails.append(x)  # longer than anything so far
        else:
            tails[k] = x  # same length, lower ending
    return len(tails)
 
lis_length_fast([5, 2, 8, 6, 3, 6, 9, 7])  # 4
ApproachTimeSpaceWhy
Table of len[i]O(n²)O(n)Each of the n cells looks back at up to n earlier cells. It is easy to walk back and list the sequence.
Tails with binary searchO(n log n)O(n)Each value costs one binary search over at most n tails. It gives the length directly.

Variants and when LIS does not apply

Non-decreasing instead of strictly increasing

The versions above require each value to be strictly larger than the one before. If equal values are allowed, as in "longest non-decreasing subsequence", change the table condition from h[j] < h[i] to h[j] <= h[i]. In the tails method, search for the first tail that is strictly greater than x (bisect_right in Python) instead of the first tail that is greater than or equal to it. Using the wrong search turns an equal value into a replacement when it should be an append, and the length comes out too small.

Returning the subsequence, not just its length

With the table, store for each index the previous index that produced its best length, then start at the index with the largest len and follow those links back. The tails method can do this too: keep the index of the value in each tail slot, and when a value is placed in slot k, record the index in slot k - 1 as its predecessor. The contents of tails are not the answer, because a later replacement can leave a list that no real subsequence matches.

Counting the longest subsequences

If the question asks how many longest increasing subsequences exist, the length table is not enough. Keep a second table count[i] that holds how many subsequences of length len[i] end at i. When extending from j gives a longer length, copy count[j]. When it gives the same length as the current best, add count[j]. This stays O(n²).

Nested pairs, such as envelopes

Problems that nest items by two dimensions, such as putting one envelope inside another only when both its width and height are strictly smaller, reduce to LIS. Sort by width ascending and, for equal widths, by height descending, then run LIS on the heights. The descending order for equal widths stops two envelopes of the same width from being counted as nested.

When LIS does not apply

LIS requires the kept values to appear in the original order. If you may reorder the items freely, you can just sort them, and the answer is the number of distinct values. If the kept values must be next to each other, the problem is a longest-run problem, solved with one pass and a counter. If the problem compares two sequences instead of one, it is closer to the longest common subsequence, covered in DP on strings.

Pitfalls and nuances

In the interview

How to recognise the problem

Look for a request to find the longest, or the number of items to remove, so that a sequence ends up increasing, without moving anything. Phrases such as "in order but not necessarily adjacent", "stacking", "nesting", "chain" or "fewest removals to make it sorted" all point to LIS. Once you see that the choice at each position depends on the last chosen value, define the state as the best sequence ending at that position.

Follow-up questions

How would you return the subsequence itself? Store a predecessor index for each position along with its length, then follow the links back from the position with the largest length. In the tails method, store the index in each tail slot and the predecessor of each value at the moment it is placed. A common mistake is to print the contents of tails.

Why is it correct to replace a tail with a smaller value? The slot only records the lowest possible ending for a subsequence of that length. A lower ending can be extended by every value that the old ending could be extended by, so no future answer is lost, and the number of slots in use is still the length of the longest subsequence so far.

Can you do better than O(n log n)? In the comparison model, O(n log n) is the best possible, so the tails method is the answer interviewers expect. They usually want you to give the O(n²) table first and then improve it.

Why does the tails list stay sorted? A new value either goes after the last tail, which keeps the order, or replaces the first tail that is at least as large. The replacement is still larger than the tail before it, because that tail was smaller than the value, and it is no larger than the tail it replaced, so the order holds. Sortedness is what makes binary search valid.

What changes if equal values are allowed? Use <= in the table, and search for the first tail strictly greater than x in the tails method. Say this out loud before coding, because it is the most common place to lose points.

How does this relate to the longest common subsequence? The LIS of a sequence equals the longest common subsequence of that sequence and its sorted version with duplicates removed. That gives an O(n²) solution through DP on strings, which is slower than the tails method but sometimes a useful way to explain the idea.

Quick check

For heights [3, 1, 4, 1, 5], what is len in the O(n²) table?

The list tails is [2, 5, 9] and the next value is 6. What happens?

Why does len[i] mean the longest sequence that ends at i, rather than the longest within the first i values?

What to practise next

If the tails search was hard to follow, revisit Binary Search, in particular the version that finds the first position where a condition holds. Then try Typing Class Progress, and write the five steps of the table in words before any code.