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
23 changes: 23 additions & 0 deletions problem52.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class BSTIterator:
def __init__(self, root):
self.st = []
self.dfs(root)

def dfs(self, root):
while root:
self.st.append(root)
root = root.left

def next(self):
temp = self.st.pop()
self.dfs(temp.right)
return temp.val

def hasNext(self):
return len(self.st) > 0

# Time Complexity:
# amortized O(1)

# Space Complexity:
# O(h)
50 changes: 50 additions & 0 deletions problem53.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from typing import Optional


class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next:
return

slow = head
fast = head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

#now slow will point to the middle node
prev = None
curr = slow.next

while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp

slow.next = None

l1 = head
l2 = prev


while l2:#l2 will be slower or same size
temp1 = l1.next

l1.next = l2
l2 = l2.next
l1.next.next = temp1

l1 = temp1

# Time Complexity: O(N)
# Space Complexity: O(1)
Empty file added problem54.py
Empty file.
46 changes: 46 additions & 0 deletions problem55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:

if not headA or not headB:
return

curr = headA
lengthA = 0

while curr:
lengthA += 1
curr = curr.next

lengthB = 0
curr = headB

while curr:
lengthB += 1
curr = curr.next

slow = headA
fast = headB

while lengthA > lengthB:
slow = slow.next
lengthA -= 1

while lengthB > lengthA:
fast = fast.next
lengthB -= 1


while slow != fast:
slow = slow.next
fast = fast.next

return slow

# Time Complexity : O(m+n)
# Space Complexity: O(1)