From 6817d70456167627e92a2ca55d04ce3922c4c4de Mon Sep 17 00:00:00 2001 From: sahabyte Date: Tue, 27 Sep 2022 17:24:35 +0500 Subject: [PATCH] done with q1,q2,q3 --- Q1/solution.py | 23 +++++++++++++++++++++++ Q2/solution.py | 16 +++++++++++++++- Q3/solution.py | 22 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/Q1/solution.py b/Q1/solution.py index 4429a19..5e833c7 100644 --- a/Q1/solution.py +++ b/Q1/solution.py @@ -1 +1,24 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Mon Sep 26 21:33:58 2022 + +@author: sahab +""" + ## Add code below with answer clearly stated + +def factorial(n): + if n <= 1: + return 1 + else: + return n * factorial(n-1) + +def sum_of_digit(n): + return 0 if n == 0 else int(n % 10) + sum_of_digit(int(n / 10)) + +x = sum_of_digit(factorial(10)) +assert x == 27 + +x = sum_of_digit(factorial(100)) +assert x == 675 diff --git a/Q2/solution.py b/Q2/solution.py index dd114fb..6949aa9 100644 --- a/Q2/solution.py +++ b/Q2/solution.py @@ -5,4 +5,18 @@ # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: - + if self.head is None: + return + index = 0 + current = self.head + + while current.next and index < n: + previous = current + current = current.next + index += 1 + + if index == 0: + self.head = self.head.next + else: + previous.next = current.next + diff --git a/Q3/solution.py b/Q3/solution.py index 18ab591..337b155 100644 --- a/Q3/solution.py +++ b/Q3/solution.py @@ -1,3 +1,25 @@ class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + le1, le2 = len(nums1), len(nums2) + total = le1 + le2 + half = total // 2 + if le1 < le2: + return self.findMedianSortedArrays(nums2, nums1) + l, r = 0, len(nums1) - 1 + while True: + i = (l + r) // 2 + j = half - i - 2 + + aleft = nums1[i] + aright = nums1[i+1] + bleft = nums1[j] + bright = nums1[j+1] + if aleft <= bright and bleft <= aright: + if total % 2 == 0: + return min(aright, bright) + return (max(aleft, bleft) + min(aright, bright)) / 2 + elif aleft > bright: + r = i - 1 + else: + l = i + 1 \ No newline at end of file