Skip to content

Commit 8fb2b3b

Browse files
committed
solve: linkedListCycle, findMinimumInRotatedSortedArray
1 parent f2b9477 commit 8fb2b3b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time Complexity: O(log n) - using binary search, so cut the search space in half each time.
2+
# Space Complexity: O(1) - only use a few variables (low, high, mid), no extra space.
3+
4+
class Solution:
5+
def findMin(self, nums: List[int]) -> int:
6+
low = 0
7+
# start with the full range of the array
8+
high = len(nums) - 1
9+
10+
# find the middle index
11+
while low < high:
12+
mid = low + (high - low) // 2
13+
14+
# if mid is greater than the last element, the min must be on the right
15+
if nums[mid] > nums[high]:
16+
# move the low pointer to the right
17+
low = mid + 1
18+
else:
19+
# min could be mid or in the left part
20+
high = mid
21+
# low and high converge to the minimum element
22+
return nums[low]

linked-list-cycle/yolophg.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time Complexity: O(n) - traverse the linked list at most once.
2+
# Space Complexity: O(1) - only use two pointers, no extra memory.
3+
4+
class Solution:
5+
def hasCycle(self, head: Optional[ListNode]) -> bool:
6+
# two pointers for fast moves twice as fast as slow.
7+
fast = head
8+
slow = head
9+
10+
# loop the list while fast and fast.next exist.
11+
while fast and fast.next:
12+
# move fast pointer two steps.
13+
fast = fast.next.next
14+
# move slow pointer one step.
15+
slow = slow.next
16+
17+
# if they meet, there's a cycle.
18+
if fast == slow:
19+
return True
20+
return False
21+

0 commit comments

Comments
 (0)