File tree 5 files changed +149
-0
lines changed
search-in-rotated-sorted-array
5 files changed +149
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(V + E) - visit each course once and process all edges
2
+ # Space Complexity: O(V + E) - storing the graph + recursion stack (worst case)
3
+
4
+ class Solution :
5
+ def canFinish (self , numCourses : int , prerequisites : List [List [int ]]) -> bool :
6
+
7
+ # Build the adjacency list (prereq map)
8
+ preMap = {i : [] for i in range (numCourses )}
9
+ for crs , pre in prerequisites :
10
+ preMap [crs ].append (pre )
11
+
12
+ # tracks courses currently being checked (for cycle detection)
13
+ visited = set ()
14
+
15
+ def dfs (crs ):
16
+ # found a cycle
17
+ if crs in visited :
18
+ return False
19
+ # no more prereqs left
20
+ if preMap [crs ] == []:
21
+ return True
22
+
23
+ # mark as visiting
24
+ visited .add (crs )
25
+
26
+ # check all prereqs for this course
27
+ for pre in preMap [crs ]:
28
+ if not dfs (pre ):
29
+ # cycle detected, return False
30
+ return False
31
+
32
+ # done checking, remove from visited
33
+ visited .remove (crs )
34
+ # mark as completed
35
+ preMap [crs ] = []
36
+ return True
37
+
38
+ # run dfs on every course
39
+ for crs in range (numCourses ):
40
+ if not dfs (crs ):
41
+ return False
42
+
43
+ return True
Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(N) - visit each node once.
2
+ # Space Complexity: O(N) - skewed tree, recursion goes N levels deep.
3
+
4
+ class Solution :
5
+ def invertTree (self , root : Optional [TreeNode ]) -> Optional [TreeNode ]:
6
+ if root is None :
7
+ return root # If the tree is empty, just return None.
8
+
9
+ # swap left and right child nodes.
10
+ root .left , root .right = root .right , root .left
11
+
12
+ # recursively invert left and right subtrees.
13
+ if root .left :
14
+ self .invertTree (root .left )
15
+ if root .right :
16
+ self .invertTree (root .right )
17
+
18
+ return root
Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(n) - go through the array once, checking jump reachability.
2
+ # Space Complexity: O(1) - no extra space used, just a few variables.
3
+
4
+ class Solution :
5
+ def canJump (self , nums : List [int ]) -> bool :
6
+
7
+ if len (nums ) == 1 :
8
+ # if there's only one element, we're already at the last index
9
+ return True
10
+
11
+ # start from second-to-last index
12
+ backtrack_index = len (nums ) - 2
13
+ # need to jump at least once to reach the last index
14
+ jump = 1
15
+
16
+ while backtrack_index > 0 :
17
+ # If we can jump from this position to the next "safe" spot
18
+ if nums [backtrack_index ] >= jump :
19
+ # reset jump counter since we found a new reachable point
20
+ jump = 1
21
+ else :
22
+ # otherwise, increase the jump required
23
+ jump += 1
24
+
25
+ # move one step left
26
+ backtrack_index -= 1
27
+
28
+ # finally, check if we can reach the last index from the starting position
29
+ return jump <= nums [0 ]
Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(N log N) - collecting all nodes is O(N), sorting is O(N log N)
2
+ # Space Complexity: O(N) - storing all nodes in an array
3
+
4
+ class Solution :
5
+ def mergeKLists (self , lists : List [Optional [ListNode ]]) -> Optional [ListNode ]:
6
+
7
+ arr = []
8
+
9
+ # collect all nodes from the linked lists
10
+ for node in lists :
11
+ while node :
12
+ arr .append (node )
13
+ node = node .next
14
+
15
+ # sort all nodes based on their value
16
+ arr .sort (key = lambda x : x .val )
17
+
18
+ # reconnect nodes to form the merged linked list
19
+ for i in range (len (arr ) - 1 ):
20
+ arr [i ].next = arr [i + 1 ]
21
+
22
+ return arr [0 ] if arr else None
Original file line number Diff line number Diff line change
1
+ # Time Complexity: O(log n) - using a modified binary search,
2
+ # Space Complexity: O(1) - no extra space used, just a few variables.
3
+
4
+ class Solution :
5
+ def search (self , nums : List [int ], target : int ) -> int :
6
+ # default result, in case the target isn't found
7
+ res = - 1
8
+ # set up the binary search range
9
+ left , right = 0 , len (nums ) - 1
10
+
11
+ while left <= right :
12
+ # calculate the middle index
13
+ mid = left + (right - left ) // 2
14
+
15
+ # found the target, store the index
16
+ if nums [mid ] == target :
17
+ res = mid
18
+
19
+ # check if the left half is sorted
20
+ if nums [left ] <= nums [mid ]:
21
+ if nums [left ] <= target < nums [mid ]:
22
+ # target in the left half, move right pointer
23
+ right = mid - 1
24
+ else :
25
+ # otherwise, search in the right half
26
+ left = mid + 1
27
+
28
+ # otherwise, the right half must be sorted
29
+ else :
30
+ if nums [mid ] < target <= nums [right ]:
31
+ # target in the right half, move left pointer
32
+ left = mid + 1
33
+ else :
34
+ # otherwise, search in the left half
35
+ right = mid - 1
36
+
37
+ return res
You can’t perform that action at this time.
0 commit comments