diff --git a/Q1/solution.py b/Q1/solution.py index 4429a19..875c018 100644 --- a/Q1/solution.py +++ b/Q1/solution.py @@ -1 +1,18 @@ +# Video explaination: https://www.youtube.com/watch?v=2r5YV5h_-1I ## Add code below with answer clearly stated +def fact(n): + if n==1: + return 1 + else: + return n*fact(n-1) +def sumDigits(n): + if(n==0): + return 0 + mod = n%10 + return mod + sumDigits((n-mod)/10) + +if __name__ == '__main__': + i = fact(100) + sum = sumDigits(i) + print(i) # 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 + print(sum) # 675 diff --git a/Q2/solution.py b/Q2/solution.py index dd114fb..ecd8fd3 100644 --- a/Q2/solution.py +++ b/Q2/solution.py @@ -1,3 +1,6 @@ +# Video https://www.youtube.com/watch?v=-HyzeXs3xog + +# Executed this solution on leetcode and it worked fine there.. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): @@ -5,4 +8,16 @@ # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + fast = slow = head + for _ in range(n): + fast = fast.next + if not fast: + return head.next + + while fast.next: + fast = fast.next + slow = slow.next + + slow.next = slow.next.next + return head diff --git a/Q3/solution.py b/Q3/solution.py index 18ab591..30cc306 100644 --- a/Q3/solution.py +++ b/Q3/solution.py @@ -1,3 +1,41 @@ +from typing import List + +# code taken from https://github.com/neetcode-gh/leetcode/blob/main/python/4-median-of-two-sorted-arrays.py +# https://www.youtube.com/watch?v=q6IEA26hvXc video explaination +# My explaination: https://www.youtube.com/watch?v=yqj1h_kw_KY + class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: - + A, B = nums1, nums2 + total = len(nums1) + len(nums2) + half = total // 2 + + if len(B) < len(A): + A, B = B, A + + l, r = 0, len(A) - 1 + while True: + i = (l + r) // 2 # A + j = half - i - 2 # B + + Aleft = A[i] if i >= 0 else float("-infinity") + Aright = A[i + 1] if (i + 1) < len(A) else float("infinity") + Bleft = B[j] if j >= 0 else float("-infinity") + Bright = B[j + 1] if (j + 1) < len(B) else float("infinity") + + # partition is correct + if Aleft <= Bright and Bleft <= Aright: + # odd + if total % 2: + return min(Aright, Bright) + # even + return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 + elif Aleft > Bright: + r = i - 1 + else: + l = i + 1 + +ans = Solution() +arr1 = [-5, 3, 6, 12, 15] +arr2 = [-12, -10, -6, -3, 4, 10] +print("Median of the two arrays is {}".format(ans.findMedianSortedArrays(arr1, arr2)))