diff --git a/problem52.py b/problem52.py new file mode 100644 index 00000000..67ed330d --- /dev/null +++ b/problem52.py @@ -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) \ No newline at end of file diff --git a/problem53.py b/problem53.py new file mode 100644 index 00000000..eedef58d --- /dev/null +++ b/problem53.py @@ -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) \ No newline at end of file diff --git a/problem54.py b/problem54.py new file mode 100644 index 00000000..e69de29b diff --git a/problem55.py b/problem55.py new file mode 100644 index 00000000..fabc78d9 --- /dev/null +++ b/problem55.py @@ -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) \ No newline at end of file