Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions cycle2.py
Original file line number Diff line number Diff line change
@@ -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



27 changes: 27 additions & 0 deletions remove_nth_from_end.py
Original file line number Diff line number Diff line change
@@ -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

32 changes: 32 additions & 0 deletions reverse_ll.py
Original file line number Diff line number Diff line change
@@ -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