1. Understand the Goal: The user wants a program to find the Longest Increasing Subsequence (LIS) of a given sequence of numbers.
-
Identify the Algorithm:
- Naive Approach: Recursion/Backtracking. Check every subsequence. Time complexity: O(2n). Too slow for practical use.
- Dynamic Programming (DP):
dp[i] stores the length of the LIS ending at index i.
- Transition:
dp[i] = 1 + max(dp[j]) for all j < i where arr[j] < arr[i].
- Time complexity: O(n2). Space complexity: O(n).
- Pros: Easier to understand, easier to reconstruct the actual sequence.
- Patience Sorting / Binary Search:
- Maintain a
tails array where tails[i] is the smallest tail of all increasing subsequences of length i+1.
- Iterate through the input. For each number
x:
- If
x is larger than all elements in tails, append it (increase length).
- If
x is not larger, replace the first element in tails which is ≥x (using binary search).
- Time complexity: O(nlogn). Space complexity: O(n).
-
Select the Language: Python is the most pseudo-code-like and easy to read for general algorithms. C++ is also good for performance demonstration. I will provide the Python solution as the primary one because it's most accessible, but I might explain the logic clearly so it can be translated. Actually, providing the O(n2) solution is often better for educational purposes because reconstructing the path in the O(nlogn) solution adds complexity that confuses beginners.
- Decision: I will provide the Dynamic Programming approach. It strikes the best balance between efficiency for moderate inputs and ease of understanding/reconstructing the subsequence.
-
Drafting the Code (O(n2) DP approach):
- Input: A list of numbers.
- Data structures:
dp: array of 1s (lengths).
parent: array to store the index of the previous element in the LIS (for reconstruction).
- Logic:
- Loop
i from 0 to n-1.
- Loop
j from 0 to i-1.
- If
arr[j] < arr[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
- Reconstruction:
- Find index
max_index corresponding to max(dp).
- Backtrack using
parent array.
- Reverse the result.
-
Refining the Explanation:
- State the complexity (O(n2)).
- Explain the logic clearly.
- Provide an example usage.
-
Wait, what about the O(nlogn) method?
While O(n2) is standard, O(nlog is the "optimal" solution. However, getting the (not just length) with is non-trivial (requires maintaining an array of indices).
-
Writing the Code:
def longest_increasing_subsequence(nums):
if not nums:
return []
n = len(nums)
# dp[i] stores the length of the LIS ending at index i
dp = [1] * n
# parent[i] stores the index of the previous element in the LIS
parent = [-1] * n
max_len = 0
end_index = 0
for i in range(n):
for j in range(i):
if nums[j] < nums[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
if dp[i] > max_len:
max_len = dp[i]
end_index = i
# Reconstruct the sequence
lis = []
curr = end_index
while curr != -1:
lis.append(nums[curr])
curr = parent[curr]
return lis[::-1] # Reverse to get correct order
-
Reviewing Edge Cases:
- Empty list: Handled.
- Single element: Handled (loops won't run effectively, returns the element).
- Descending order: Returns the first element (length 1). Correct.
-
Final Polish: Add comments, explain the time complexity, and provide example input/output.
-
Bonus: Maybe provide the C++ version too? No, usually one clear Python implementation is best unless requested. I'll stick to Python but make it very clear.
Let's double check the O(NlogN) reconstruction logic just in case the user wants "the best".
It involves tails array (stores indices) and prev_indices array.
It's actually doable in ~20 lines, but significantly harder to explain than the DP one.
I will stick to O(N2) for clarity, as is standard for "find the subsequence" questions.
Structure of the answer:
- Intro.
- Python Code (DP approach).
- Explanation of how it works.
- Complexity analysis.
- Example run.
Let's write it out.
Here is a solution in Python using .
This approach not only calculates the length of the subsequence but also reconstructs the actual numbers involved.
The Algorithm (O(n²))
This is the standard approach for this problem.
- Create an array
dp where dp[i] represents the length of the longest increasing subsequence ending at index i.
- Create an array
parent to keep track of the previous index in the subsequence (this allows us to backtrack and print the sequence later).
- For every element, compare it with all previous elements. If a previous element is smaller, check if extending the sequence from that previous element results in a longer path than the current one.
Python Implementation
def find_longest_increasing_subsequence(arr):
if not arr:
return []
n = len(arr)
# dp[i] stores the length of the LIS ending at index i
dp = [1] * n
# parent[i] stores the index of the previous element in the LIS ending at i
parent = [-1] * n
# Compute LIS values in bottom-up manner
for i in range(1, n):
for j in range(i):
# If arr[i] can extend the sequence ending at arr[j]
if arr[i] > arr[j] and dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
parent[i] = j
# Find the index of the maximum value in dp
max_length = max(dp)
max_index = dp.index(max_length)
# Reconstruct the sequence by backtracking
sequence = []
curr = max_index
while curr != -1:
sequence.append(arr[curr])
curr = parent[curr]
# Since we backtracked, the sequence is in reverse order
return sequence[::-1]
# --- Example Usage ---
if __name__ == "__main__":
input_list = [10, 22, 9, 33, 21, 50, 41, 60, 80]
result = find_longest_increasing_subsequence(input_list)
print(f"Input: {input_list}")
print(f"Longest Increasing Subsequence: {result}")
print(f"Length: {len(result)}")
How it works (Step-by-Step)
Let's trace a small portion of the input [10, 22, 9, 33]:
- Start:
dp is [1, 1, 1, 1] (every number is a sequence of length 1 by itself).
- Process 22: It is bigger than 10. We can extend 10.
dp becomes [1, 2, 1, 1].
- Process 9: It is smaller than 10 and 22. It cannot extend them.
dp remains [1, 2, 1, 1].
- Process 33:
- Compare with 10: 33 > 10. Potential length = 1 + 1 = 2.
- Compare with 22: 33 > 22. Potential length = 2 (length at 22) + 1 = 3.
- Compare with 9: 33 > 9. Potential length = 1 + 1 = 2.
- The maximum option is 3. So
dp becomes [1, 2, 1, 3].
Complexity
- Time Complexity: O(n2) — We use two nested loops to compare every element against every previous element.
- Space Complexity: O(n) — We store the
dp and parent arrays.
Note: There is a more advanced algorithm using Binary Search and a "Patience Sorting" technique that runs in O(nlogn), but the Dynamic Programming approach shown above is generally easier to understand and implement for reconstructing the actual sequence.