Skip to content

Commit

Permalink
solve: linkedListCycle, findMinimumInRotatedSortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
helenapark0826 committed Feb 8, 2025
1 parent f2b9477 commit fb9f931
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions find-minimum-in-rotated-sorted-array/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Time Complexity: O(log n) - using binary search, so cut the search space in half each time.
# Space Complexity: O(1) - only use a few variables (low, high, mid), no extra space.

class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
# start with the full range of the array
high = len(nums) - 1

# find the middle index
while low < high:
mid = low + (high - low) // 2

# if mid is greater than the last element, the min must be on the right
if nums[mid] > nums[high]:
# move the low pointer to the right
low = mid + 1
else:
# min could be mid or in the left part
high = mid
# low and high converge to the minimum element
return nums[low]
21 changes: 21 additions & 0 deletions linked-list-cycle/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Time Complexity: O(n) - traverse the linked list at most once.
# Space Complexity: O(1) - only use two pointers, no extra memory.

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# two pointers for fast moves twice as fast as slow.
fast = head
slow = head

# loop the list while fast and fast.next exist.
while fast and fast.next:
# move fast pointer two steps.
fast = fast.next.next
# move slow pointer one step.
slow = slow.next

# if they meet, there's a cycle.
if fast == slow:
return True
return False

0 comments on commit fb9f931

Please sign in to comment.