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
28 changes: 28 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#Problem 206. REVERSE LINKED LIST
# TIME COMPELXITY: O(N) where N denotes the number of nodes in the given linked list
# SPACE COMPLEXITY: O(N) since we are doing recursion which will be having stack logic



# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
return self.helper(head,None)

def helper(self,curr,prev):
if curr is None:
return prev

temp=curr.next
curr.next=prev
prev=curr
curr=temp
return self.helper(curr,prev)
38 changes: 38 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#Problem 19. REMOVE NTH NODE FROM END OF LIST
# TIME COMPELXITY: O(N) where N denotes the number of nodes present
# SPACE COMPLEXITY: O(1) as we are using pointers


# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: Optional[ListNode]
:type n: int
:rtype: Optional[ListNode]
"""
dummy=ListNode(-1)
dummy.next=head
counter=0
fast=dummy
slow=dummy

while counter<=n:
fast=fast.next
counter+=1

while fast is not None:
slow=slow.next
fast=fast.next

# temp = slow.next
# slow.next = slow.next.next
# temp.next = None

slow.next = slow.next.next

return dummy.next
41 changes: 41 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#Problem 142. LINKED LIST CYCLE II
# TIME COMPELXITY: O(N) where N denotes the number of nodes
# SPACE COMPLEXITY: O(1) as we are not using any extra space we are only using pointers which takes O(1) of space


# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if head is None:
return None
fast=head
slow=head
flag=False

while fast.next is not None and fast.next.next is not 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