Skip to problem
←

Longest Increasing Subsequence

Medium 0 attempts

Given an integer array nums, return the length of its longest strictly increasing subsequence.

A subsequence keeps the original relative order but may skip elements. You may not sort or rearrange elements. Every chosen value must be greater than the previous one; equal values cannot extend the subsequence.

For [10,9,2,5,3,7,101,18], one longest subsequence is [2,3,7,18], with length 4. You only need to return its length, not the subsequence itself. For [2,2,2], return 1.

Function contract

Implement longestIncreasingSubsequence(nums). Receive a nonempty array of integers.

Output: Return the maximum number of elements in a strictly increasing subsequence.

Example 1

Input
nums = [10,9,2,5,3,7,101,18]
Output
4

Example 2

Input
nums = [0,1,0,3,2,3]
Output
4
Constraints
  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

Approach: Binary Search (Patience Sort)

Maintain a tails array where tails[i] is the smallest tail element of all increasing subsequences of length i+1. For each number, find the first tail greater than or equal to it. Replace that tail, or append if all tails are smaller. An equal value replaces an existing tail instead of extending the sequence, enforcing strict increase. A smaller tail preserves more opportunities to extend a subsequence later.

The tails entries need not themselves form a subsequence of the input; only the array length is the answer.

javascript
function longestIncreasingSubsequence(nums) {
  const tails = [];
  for (const num of nums) {
    let lo = 0, hi = tails.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid] < num) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = num;
  }
  return tails.length;
}

Time Complexity: O(n log n)

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript