diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..9d428db9 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,21 @@ +# Reverse Linked List +# Time complexity On +# SPace complexity -> O1 +# Logic -> Maintain prev and curr pointer, eveery loop update next of curre to prev, and move both 1 step ahead while maintaing +# the pointer to the next element of the current node using tmp +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 !=None: + tmp = curr.next + curr.next = prev + prev = curr + curr = tmp + return prev \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..d83ebbb3 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,30 @@ +# Remove Nth Node From End of List + +# Time complexity -> O(2n) -> O(n) +# Space complexity -> O1 +# Logic -> iterate once find the length, in 2nd iteration stop at the desired position drop the node + +# 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]: + length = 0 + + curr = head + while curr!=None: + length+=1 + curr=curr.next + dummyNode = ListNode(-1,head) + curr=dummyNode + while length > n: + length-=1 + curr=curr.next + print(curr) + curr.next=curr.next.next + + return dummyNode.next \ No newline at end of file diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..76c716f3 --- /dev/null +++ b/Problem3.py @@ -0,0 +1,37 @@ +#Linked List Cycle II + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +# Time -> On +# Space -> O1 +# Logic -> Take 2 pointers, slow and fast, fast is of double speed. If they meeet, means cycle else No cycle +# if cycle move fast to begining now move at same speed they'll meet at the junction + + +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + slow = head + fast = head + + isCyclic = False + while fast != None and fast.next!=None: + slow = slow.next + fast = fast.next.next + if slow == fast: + isCyclic = True + break + + if not isCyclic: + return None + + + fast = head + while fast != slow: + slow=slow.next + fast=fast.next + + return fast \ No newline at end of file