File tree 5 files changed +258
-0
lines changed
container-with-most-water
design-add-and-search-words-data-structure
longest-increasing-subsequence
5 files changed +258
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 11. Container With Most Water
3
+
4
+ use two pointers to find the maximum area.
5
+
6
+ > **move the shorter line inward:**
7
+ > - area is determined by the shorter line.
8
+ > - move the shorter line inward => may find a taller line that can increase the area.
9
+
10
+ ## Time and Space Complexity
11
+
12
+ ```
13
+ TC: O(n)
14
+ SC: O(1)
15
+ ```
16
+
17
+ ### TC is O(n):
18
+ - while loop iterates through the height array once. = O(n)
19
+
20
+ ### SC is O(1):
21
+ - using two pointers and max_area variable. = O(1)
22
+ '''
23
+
24
+ class Solution :
25
+ def maxArea (self , height : List [int ]) -> int :
26
+ left = 0
27
+ right = len (height ) - 1
28
+ max_area = 0
29
+
30
+ while left < right : # TC: O(n)
31
+ distance = right - left
32
+ current_area = min (height [left ], height [right ]) * distance
33
+ max_area = max (current_area , max_area )
34
+
35
+ if height [left ] < height [right ]:
36
+ left += 1
37
+ else :
38
+ right -= 1
39
+
40
+ return max_area
Original file line number Diff line number Diff line change
1
+ '''
2
+ # 211. Design Add and Search Words Data Structure
3
+
4
+ use trie to perform add and search operations on words.
5
+ use recursive dfs to search for words with "." wildcards.
6
+
7
+ ## Time and Space Complexity
8
+
9
+ ### addWord
10
+
11
+ ```
12
+ TC: O(n)
13
+ SC: O(n)
14
+ ```
15
+
16
+ ### TC is O(n):
17
+ - iterating through each character of the word. = O(n)
18
+
19
+ ### SC is O(n):
20
+ - storing the word in the trie. = O(n)
21
+
22
+ ### search
23
+
24
+ ```
25
+ TC: O(n)
26
+ SC: O(n)
27
+ ```
28
+
29
+ ### TC is O(n):
30
+ - dfs iterates through each character of the word. = O(n)
31
+ - if char is "."(wildcard) dfs iterates through all children of the current node. = O(n)
32
+
33
+ > recursion for the wildcard could involve exploring several paths.
34
+ > but time complexity is bounded by the length of the word, so it's still O(n).
35
+
36
+ ### SC is O(n):
37
+ - length of the word as recursive call stack. = O(n)
38
+ '''
39
+ class WordDictionary :
40
+ def __init__ (self ):
41
+ self .trie = {}
42
+
43
+ def addWord (self , word : str ) -> None :
44
+ node = self .trie
45
+ for char in word : # TC: O(n)
46
+ if char not in node :
47
+ node [char ] = {}
48
+ node = node [char ]
49
+ node ["$" ] = True
50
+
51
+ def search (self , word : str ) -> bool :
52
+ def dfs (node , i ) -> bool :
53
+ if not isinstance (node , dict ):
54
+ return False
55
+ if i == len (word ):
56
+ return "$" in node if isinstance (node , dict ) else False
57
+ char = word [i ]
58
+
59
+ if char == "." :
60
+ for child in node .values ():
61
+ if dfs (child , i + 1 ):
62
+ return True
63
+ return False
64
+ else :
65
+ return dfs (node [char ], i + 1 ) if char in node else False
66
+
67
+ return dfs (self .trie , 0 )
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
Original file line number Diff line number Diff line change
1
+ '''
2
+ # 54. Spiral Matrix
3
+
4
+ to traverse the matrix in a spiral order:
5
+ 1. do boundary-tracking
6
+ 2. iterate in layers
7
+ - move right, move down, move left, move up
8
+ - shrink the boundaries
9
+ 4. return the result
10
+
11
+ # Time and Space Complexity
12
+
13
+ ```
14
+ TC: O(m * n)
15
+ SC: O(1)
16
+ ```
17
+
18
+ #### TC is O(m * n):
19
+ move through the 2D matrix just once. = O(m * n)
20
+
21
+ #### SC is O(1):
22
+ result list is excluded from auxiliary space, so it's = O(1)
23
+ '''
24
+
25
+ class Solution :
26
+ def spiralOrder (self , matrix : List [List [int ]]) -> List [int ]:
27
+ top = 0
28
+ left = 0
29
+ bottom = len (matrix ) - 1
30
+ right = len (matrix [0 ]) - 1
31
+ result = [] # SC: O(1)
32
+
33
+ while top <= bottom and left <= right :
34
+ for i in range (left , right + 1 ):
35
+ result .append (matrix [top ][i ])
36
+ top += 1
37
+
38
+ for i in range (top , bottom + 1 ):
39
+ result .append (matrix [i ][right ])
40
+ right -= 1
41
+
42
+ if top <= bottom :
43
+ for i in range (right , left - 1 , - 1 ):
44
+ result .append (matrix [bottom ][i ])
45
+ bottom -= 1
46
+
47
+ if left <= right :
48
+ for i in range (bottom , top - 1 , - 1 ):
49
+ result .append (matrix [i ][left ])
50
+ left += 1
51
+
52
+ return result
Original file line number Diff line number Diff line change
1
+ '''
2
+ # 20. Valid Parentheses
3
+
4
+ use stack data structure to perform as a LIFO
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n)
10
+ SC: O(n)
11
+ ```
12
+
13
+ #### TC is O(n):
14
+ - iterating through the string just once to check if the parentheses are valid. = O(n)
15
+
16
+ #### SC is O(n):
17
+ - using a stack to store the parentheses. = the worst case is O(n)
18
+ - using a map to store the parentheses. = O(1)
19
+
20
+ > for space complexity, fixed space is O(1).
21
+ > 👉 parentheses_map is fixed and its size doesn't grow with the input size.
22
+ > 👉 if the map has much larger size? the space complexity is still O(1).
23
+ '''
24
+
25
+ class Solution :
26
+ def isValid (self , s : str ) -> bool :
27
+ stack = [] # SC: O(n)
28
+ parentheses_map = { # SC: O(1)
29
+ "(" : ")" ,
30
+ "{" : "}" ,
31
+ "[" : "]"
32
+ }
33
+
34
+ for char in s : # TC: O(n)
35
+ if char in parentheses_map :
36
+ stack .append (char )
37
+ else :
38
+ if len (stack ) == 0 or parentheses_map [stack .pop ()] != char :
39
+ return False
40
+
41
+ return not stack
You can’t perform that action at this time.
0 commit comments