To design an algorithm to find the longest increasing subsequence (LIS) in an unsorted array, there are several approaches you can take, depending on the desired balance between simplicity and efficiency.
Dynamic Programming Approach
- Initialize an array
dp: Create an array dp where dp[i] stores the length of the longest increasing subsequence ending at index i.
- Fill the
dp array:
- Set each
dp[i] to 1 initially, because the minimum LIS ending at each element is the element itself.
- For each element
i in the array, iterate through all previous elements j (from 0 to i-1):
- If
arr[j] < arr[i], then arr[i] can extend the subsequence ending at arr[j], so update dp[i] as dp[i] = max(dp[i], dp[j] + 1).
- Find the result: The length of the longest increasing subsequence will be the maximum value in the
dp array.
- Time Complexity: O(n^2), where
n is the number of elements in the array. This is because of the nested loop structure.
Optimized Approach Using Binary Search
To improve upon the O(n^2) time complexity, you can use a combination of a list to track the ends of potential subsequences and binary search. This approach is known as Patience Sorting-like method or using a dynamic programming with a binary search:
- Initialize a list
tails: This list will keep track of the smallest possible tail value for all increasing subsequences of different lengths observed so far.
- Iterate over each element
x in the array:
- Use binary search (from libraries like Python's
bisect) to find the position pos to either replace an element of tails or extend it.
- If
x is larger than the largest element in tails, append it to tails.
- Otherwise, replace the element at the found position with
x to maintain the smallest possible values, which allows for more room for growth of subsequences.
- Result: The length of the
tails list at the end will be the length of the longest increasing subsequence.
- Time Complexity: O(n log n), where
n is the number of elements in the array. The binary search within this algorithm is what provides the log factor.
Code Example (Optimized Version in Python):
Here's how you could implement the O(n log n) approach:
from bisect import bisect_left
def length_of_lis(nums):
tails = []
for x in nums:
pos = bisect_left(tails, x)
if pos == len(tails):
tails.append(x)
else:
tails[pos] = x
return len(tails)
# Example usage
arr = [10, 9, 2, 5, 3, 7, 101, 18]
print(length_of_lis(arr)) # Output: 4 (LIS is [2, 3, 7, 101])
This code uses the bisect_left function to efficiently find the position pos to update the tails list, ensuring an O(n log n) complexity. The resulting tails list itself does not contain the LIS, but its length provides the length of the LIS.