diff --git a/cycle2.py b/cycle2.py new file mode 100644 index 00000000..944f4a9e --- /dev/null +++ b/cycle2.py @@ -0,0 +1,32 @@ +""" +time = o(n) +space = o(1) +we maintain slow and fast pointers and find if there is a cycle in the linked list, if there is a cycle slow and fast meet at a node. +we then start from head with a new pointer and then move slow and new pointer one node at a time, till they meet and they will meet at the start of the cycle +the algorithm behind this is floyd's tortoise algorithm +""" +from typing import Optional +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + fast = slow = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow==fast: + break + if not fast or not fast.next: + return None + p1 = head + while p1!=slow: + p1=p1.next + slow = slow.next + return slow + + + \ No newline at end of file diff --git a/remove_nth_from_end.py b/remove_nth_from_end.py new file mode 100644 index 00000000..49329024 --- /dev/null +++ b/remove_nth_from_end.py @@ -0,0 +1,27 @@ +""" +space - o(1) +time - o(n) +we keep a dummy node and use two pointers, move one pointer to nth position from head (with head as 1) and once this happens, we move both pointers one node +at a time till second pointer reaches the last node, at this point we remove the node next to the first pointer. +""" +from typing import Optional +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + dummy = ListNode(0) + dummy.next = head + p1 = head + p2 = dummy + for _ in range(1,n): + p1 = p1.next + while p1 and p1.next: + p1 = p1.next + p2 = p2.next + if p2.next: + p2.next = p2.next.next + return dummy.next + \ No newline at end of file diff --git a/reverse_ll.py b/reverse_ll.py new file mode 100644 index 00000000..00baee05 --- /dev/null +++ b/reverse_ll.py @@ -0,0 +1,32 @@ +""" +time - o(n) +space - o(1) +we take three variables, current, previous and next, we basically make the current node's next as previous and for the next iteration make next as current and current as previous +we maintain a dummy node at the start to return the result +""" +from typing import Optional +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def __init__(self): + self.new_head = None + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head: + return head + self.helper(head) + return self.new_head + + def helper(self, head): + if not head.next: + self.new_head = head + return head + + node = self.helper(head.next) + node.next = head + head.next = None + return head + + \ No newline at end of file