Bitpath

Lesson 2 · Unit 04

Longest increasing subsequence

An O(n²) table, then the O(n log n) idea

12 exercisesabout 3 min

What you practise

  • The O(n²) table and the O(n log n) idea

Try a question from this lesson

Pick one

dp[i] is the length of the longest increasing subsequence that ends exactly at index i. For the list [2, 5, 3], what is dp?

Hint

For each index, find the best chain that ends on that number. Only smaller numbers before it can come first.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Extend every smaller neighbour

Start every cell at 1. For each index i, look back at every earlier index j. If the number at j is smaller, the subsequence ending at j can be extended by the number at i.

Keep the best extension. The answer is the largest cell in the table.

def lis(nums):
    dp = [1] * len(nums)
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] < nums[i]:
                best = dp[j] + 1
                dp[i] = max(dp[i], best)
    return max(dp, default=0)
function lis(nums) {
  const dp = nums.map(() => 1);
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < i; j++) {
      if (nums[j] < nums[i]) {
        const best = dp[j] + 1;
        dp[i] = Math.max(dp[i], best);
      }
    }
  }
  return Math.max(0, ...dp);
}
function lis(nums: number[]): number {
  const dp = nums.map(() => 1);
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < i; j++) {
      if (nums[j] < nums[i]) {
        const best = dp[j] + 1;
        dp[i] = Math.max(dp[i], best);
      }
    }
  }
  return Math.max(0, ...dp);
}

Python notemax(dp, default=0) returns 0 for an empty list. Plain max([]) raises a ValueError.

JavaScript noteMath.max(0, ...dp) spreads the cells into arguments. The leading 0 covers an empty list, where Math.max() alone gives -Infinity.

TypeScript notenums.map(() => 1) is inferred as number[], the same length as nums, with no annotation.

Concept

The O(n log n) idea

Keep a sorted list tails, where tails[k] is the smallest number that can end an increasing subsequence of length k + 1. A smaller tail is easier to extend.

For each x, binary search for the first tail that is not smaller than x and replace it. If there is none, append x. The length of tails is the answer.

from bisect import bisect_left

def lis(nums):
    tails = []
    for x in nums:
        k = bisect_left(tails, x)
        if k == len(tails):
            tails.append(x)
        else:
            tails[k] = x
    return len(tails)
function lis(nums) {
  const tails = [];
  for (const x of nums) {
    let lo = 0;
    let hi = tails.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = x;
  }
  return tails.length;
}
function lis(nums: number[]): number {
  const tails: number[] = [];
  for (const x of nums) {
    let lo = 0;
    let hi = tails.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = x;
  }
  return tails.length;
}

Python notebisect_left(tails, x) is the standard library binary search: the index of the first item that is not smaller than x.

JavaScript noteJavaScript has no built-in binary search, so the loop is written out. tails[lo] = x appends when lo equals the length.

TypeScript noteAn empty array literal needs number[]; otherwise TypeScript has nothing to infer the element type from.

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy