300. Longest Increasing Subsequence
Asked at 25Microsoft56Google52Amazon52Bloomberg50Meta40PayPal92Revolut84Infosys58Samsung100TikTok86Squarepoint Capital77Huawei76ByteDance59Morgan Stanley54Walmart Labs53Intuit52Agoda48Nvidia48Accenture44tcs42Salesforce41Oracle41Visa39Yandex36Goldman Sachs21
Problem
Return the length of the longest strictly increasing subsequence of nums (elements in order, not necessarily adjacent).
Example: [10,9,2,5,3,7,101,18] → 4 (e.g. 2, 3, 7, 101)
Constraints: n ≤ 2500. Follow-up: O(n log n).
O(n²): dp[i] = 1 + max(dp[j]) for j < i, nums[j] < nums[i]. O(n log n): tails[k] = smallest tail of an increasing subsequence of length k+1; binary-search each number's position and overwrite.
nums 10 9 2 5 3 7 101 18
tails [10] -> [9] -> [2] -> [2,5] -> [2,3] -> [2,3,7] -> [2,3,7,101] -> [2,3,7,18] len 4
Complexity: O(n log n).
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
tails = []
for x in nums:
i = bisect.bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
assert Solution().lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]) == 4
assert Solution().lengthOfLIS([0, 1, 0, 3, 2, 3]) == 4
assert Solution().lengthOfLIS([7, 7, 7, 7]) == 1
class Solution {
public int lengthOfLIS(int[] nums) {
int[] tails = new int[nums.length];
int len = 0;
for (int x : nums) {
int lo = 0, hi = len;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (tails[mid] >= x) hi = mid; else lo = mid + 1;
}
tails[lo] = x;
if (lo == len) len++;
}
return len;
}
}
func lengthOfLIS(nums []int) int {
tails := []int{} // tails[k] = smallest tail of an increasing subsequence of length k+1
for _, x := range nums {
i := sort.SearchInts(tails, x)
if i == len(tails) {
tails = append(tails, x)
} else {
tails[i] = x
}
}
return len(tails)
}