Skip to content

Commit 0bdc50c

Browse files
committed
add solution: longest-increasing-subsequence
1 parent ee6f6e4 commit 0bdc50c

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'''
2+
# 300. Longest Increasing Subsequence
3+
4+
use the sub list to store current LIS.
5+
iterate nums's elements and find the position of the current number in the subsequence. (using a binary search helper function)
6+
after the iteration finishes, return the length of the subsequence.
7+
8+
> **helper function explanation:**
9+
> ```py
10+
> position = bisectLeft(sub, num)
11+
> ```
12+
> bisectLeft is doing binary search that finds the leftmost position in a sorted list.
13+
>if the position is the end of the subsequence, append the current number to the subsequence.
14+
>if the position is not the end of the subsequence, replace the number at the position with the current number.
15+
16+
> **python's bisect module:**
17+
> https://docs.python.org/3.10/library/bisect.html
18+
19+
## Time and Space Complexity
20+
21+
```
22+
TC: O(n log n)
23+
SC: O(n)
24+
```
25+
26+
#### TC is O(n log n):
27+
- iterating through the nums list to find the position of the current number. = O(n)
28+
- using a binary search helper function to find the position of the current number. = O(log n)
29+
30+
#### SC is O(n):
31+
- using a list to store the subsequence. = O(n) in the worst case
32+
'''
33+
class Solution:
34+
def lengthOfLIS(self, nums: List[int]) -> int:
35+
sub = [] # SC: O(n)
36+
37+
for num in nums: # TC: O(n)
38+
pos = self.bisectLeft(sub, num) # bisect.bisect_left(sub, num) = TC: O(log n)
39+
if pos == len(sub):
40+
sub.append(num)
41+
else:
42+
sub[pos] = num
43+
44+
return len(sub)
45+
46+
def bisectLeft(self, list, target) -> int:
47+
low = 0
48+
high = len(list) - 1
49+
50+
while low <= high :
51+
mid = int(low + (high - low) / 2)
52+
53+
if list[mid] < target:
54+
low = mid + 1
55+
else:
56+
high = mid - 1
57+
58+
return low

0 commit comments

Comments
 (0)