File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
longest-increasing-subsequence Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments