Longest Increasing Subsequence

Patience-sort tails — for each value, replace the leftmost tail ≥ it; final tail length is LIS.

Medium
Time O(n log n) Space O(n)
LeetCode
3 min read
dp binary-search patience-sort

Problem#

Return the length of the longest strictly-increasing subsequence.

Examples#

  • [10,9,2,5,3,7,101,18]4 (one such: [2,3,7,101]).
  • [0,1,0,3,2,3]4; [7,7,7,7]1.

Constraints#

  • 1 <= nums.length <= 2500.

Approach#

Maintain a sorted tails array where tails[k] is the smallest possible tail of any increasing subsequence of length k+1. For each value, binary-search the first tail >= value and replace it (or append if larger than all).

Solution#

Longest Increasing Subsequence
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> tails;
for (int x : nums) {
auto it = lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) tails.push_back(x);
else *it = x;
}
return tails.size();
}
};

Editorial#

tails is not necessarily a real subsequence — it just tracks the best possible tail per length. Patience sort is the conceptual model: each tails[k] is the top of the k-th pile. The trick is that the answer is just the pile count.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.