Taro Logo

Longest Increasing Subsequence

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+26
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.7K views
Topics:
ArraysBinary SearchDynamic Programming

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

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

Constraints:

  • 1 <= nums.length <= 2500
  • -104 <= nums[i] <= 104

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of the array's length, and can the input array be empty?
  2. Can the array contain negative numbers and zeros, or are we strictly dealing with positive integers?
  3. How should strictly increasing be interpreted regarding duplicate values—do duplicates break the increasing sequence or can they be skipped?
  4. Are we only required to return the length of the longest increasing subsequence, or do we also need to reconstruct and return the actual sequence itself?
  5. If multiple increasing subsequences share the exact same maximum length, does it matter which one is considered, or can we return any valid one?

Brute Force Solution

Approach

The brute force approach to finding the longest sequence of numbers that always go up involves looking at every possible combination of numbers from the list. By testing every single path, we can guarantee we find the longest one, even if it takes a lot of effort.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first number on the list.
  2. Consider all possible paths you could take by moving forward and picking numbers that are strictly larger than the ones you have chosen so far.
  3. Try every single combination of picking and skipping numbers until you have explored every possible growing chain that can be formed.
  4. As you test each combination, check how many numbers are in that specific growing chain.
  5. Keep a mental note of the length of the chain every time you find one that grows successfully.
  6. Compare all the lengths you recorded during your search.
  7. Select the largest length you found as the final answer.

Code Implementation

def length_of_longest_increasing_subsequence(sequence_numbers):
    
    def explore_all_combinations(current_index, previous_value):
        # We stop searching when we reach the end of the input list
        if current_index == len(sequence_numbers):
            return 0
            
        skip_current_choice = explore_all_combinations(current_index + 1, previous_value)
        
        take_current_choice = 0
        
        # We can only include the current number if it is strictly greater than the previous one
        if sequence_numbers[current_index] > previous_value:
            take_current_choice = 1 + explore_all_combinations(current_index + 1, sequence_numbers[current_index])
            
        # We return the maximum length found between skipping or taking the current number
        return max(skip_current_choice, take_current_choice)

    # We initiate the recursive search using a sentinel value smaller than any possible number
    return explore_all_combinations(0, float('-inf'))

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force approach explores every possible combination of picking or skipping numbers to form an increasing sequence. For each of the n elements in the array, the algorithm branches into two choices: either include the current number in the sequence or exclude it. This results in exploring a binary decision tree of depth n, leading to roughly 2ⁿ total recursive paths. Simplifying this exponential growth gives a final time complexity of O(2ⁿ).
Space Complexity
O(N) – The brute force approach relies on exploring every possible combination of numbers through recursive branching, which creates activation records on the call stack. The maximum depth of this recursion stack corresponds directly to the length of the input list, denoted as N, meaning the maximum number of nested function calls active at any single moment is proportional to N. Therefore, the auxiliary space complexity is driven entirely by the maximum depth of the recursion stack, resulting in an O(N) memory requirement.

Optimal Solution

Approach

Instead of checking every single possible sequence, the optimal approach maintains a running collection of growing piles of numbers. As you look through the items one by one, you strategically place each number into the most logical pile so that you always keep your options for future growth as open as possible.

Here's how the algorithm would work step-by-step:

  1. Begin with an empty workspace where you will organize the incoming numbers.
  2. Look at the first number and create your very first pile to hold it.
  3. Take the next number and compare it to the top values of your existing piles.
  4. If the new number is larger than the top values of all current piles, start a brand new pile to the right.
  5. If the new number is smaller than or equal to an existing pile's top value, slide it into that existing pile, replacing the current top value to make that pile stronger for the future.
  6. Repeat this process for every remaining number, always placing each one into the correct pile according to its value.
  7. Count the total number of piles you ended up creating, which instantly tells you the length of the longest increasing sequence.

Code Implementation

import bisect


def length_of_lis(sequence_numbers):
    active_piles_tops = []

    # We place each number in the best pile to keep future growth options open.
    for current_number in sequence_numbers:
        insertion_index = bisect.bisect_left(active_piles_tops, current_number)

        # A larger number extends our longest sequence by creating a new pile.
        if insertion_index == len(active_piles_tops):
            active_piles_tops.append(current_number)

        # A smaller number strengthens an existing pile to help future elements.
        else:
            active_piles_tops[insertion_index] = current_number

    return len(active_piles_tops)

Big(O) Analysis

Time Complexity
O(n log n) – For each of the n numbers in the input array, we must search our collection of piles to find where the number belongs. Since the piles always maintain sorted top values, we can use binary search which takes log n time for each element. As we iterate through all n elements and perform a binary search for each, the total operations approximate n times log n, which simplifies to O(n log n).
Space Complexity
O(n) – The auxiliary data structure driving the space usage is the workspace that organizes the incoming numbers into piles, where n represents the total number of elements in the input sequence. In the worst-case scenario where the entire input sequence is strictly increasing, every incoming number forms its own brand new pile to the right. Consequently, this temporary list storing the top values of the piles will grow to hold up to n elements. Therefore, the extra memory required scales linearly with the input size n, simplifying to Big O of n.

Edge Cases

Empty or null input array
How to Handle:
Check for null or empty input at the very beginning and return a length of zero.
Single element array
How to Handle:
The algorithm naturally processes the single element and returns a length of one.
Array with all identical elements
How to Handle:
Since the problem requires strictly increasing subsequences, duplicate values will be ignored and the length returned will be one.
Array sorted in strictly decreasing order
How to Handle:
No element can be appended to an increasing sequence, so the maximum length returned will be one.
Array with negative numbers and zeros
How to Handle:
Standard comparison operators handle negative values and zeros correctly without requiring offset adjustments.
Maximum size input array up to constraints
How to Handle:
Using the O(n log n) patience sorting approach with binary search ensures efficient scaling well within time limits.
Array with extreme boundary integer values
How to Handle:
Standard integer comparisons handle extreme positive and negative values correctly without risk of overflow.
Multiple valid increasing subsequences of the same maximum length
How to Handle:
The algorithm correctly tracks the length regardless of which alternative path achieves the maximum.
0/75 completed