diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..d19e7b6e --- /dev/null +++ b/Problem1.py @@ -0,0 +1,55 @@ +# https://leetcode.com/problems/reverse-linked-list/ + +# Time Complexity: O(2n) +# Space Complexity: O(n) + +# This problem implements reversing a linked list. This is one of the methods which use prev, curr and temp +# pointers to reverse the direction and move all 3 pointers one node at a time until it reaches end of the linked list +# Then finally the last node points to prev. Return the prev pointer which gives the reversed linked list +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + curr = head + + while curr is not None: + temp = curr.next + curr.next = prev + prev = curr + curr = temp + return prev + +# Recursive solution for reversing linked list + +class Solution: + def reverseList(self, head): + if head is None or head.next is None: + return head + + re = self.reverseList(head.next) + head.next.next = head + head.next = None + return re + +# Recursion using helper function + +class Solution: + new_head = ListNode() + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None: + return None + self.helper(head) + return self.new_head + + def helper(self, head): + if head.next is None: + self.new_head = head + return + + self.helper(head.next) + head.next.next = head + head.next = None diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..6668283f --- /dev/null +++ b/Problem3.py @@ -0,0 +1,40 @@ +# https://leetcode.com/problems/linked-list-cycle-ii/ + +# Time Complexity: O(n) +# Space Complexity: + +# This problem is to detect if a cycle exists in a singly linked list. We implement using slow and fast pointers. +# We first move slow by 1x and fast by 2x. If there is a cycle, then at some point fast and slow meet. +# If they don't meet, then we return null. Once we know the meeting point. We now assign the slow pointer to the head of the linked list. +# Slow and fast pointer both move at 1x. They will surely meet at the start node of the cycle, although the fast pointer will have some amount +# cyclical movements while the slow is approaching the cycle's start node point. + +# 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]: + + slow = head + fast = head + flag = False + while fast != None and fast.next != None: + slow = slow.next + fast = fast.next.next + if slow == fast: + flag = True + break + + if not flag: + return None + + slow = head + + while slow != fast: + slow = slow.next + fast = fast.next + + return slow \ No newline at end of file