diff --git a/merge_arrays.py b/merge_arrays.py new file mode 100644 index 00000000..349cbb15 --- /dev/null +++ b/merge_arrays.py @@ -0,0 +1,38 @@ +""" +time - o(n) +space - o(1) +set p and q to m-1 and n-1, these are pointers that point to the biggest elements in both the lists. whichever is the biggest among the two copy them to the last position in nums1. Then decrement the corresponding pointer. +the last position of the array nums1 is tracked by the pointer r = m+n-1 +""" + +from typing import List + + +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + # edge case if m=0 or n=0 + if m == 0: + nums1[0] = nums2[0] + p = m - 1 + q = n - 1 + r = m + n - 1 + while r >= 0: + if p >= 0 and q >= 0: + if nums1[p] > nums2[q]: + nums1[r] = nums1[p] + p -= 1 + else: + nums1[r] = nums2[q] + q -= 1 + r -= 1 + elif p >= 0: + nums1[r] = nums1[p] + r -= 1 + p -= 1 + elif q >= 0: + nums1[r] = nums2[q] + q -= 1 + r -= 1 diff --git a/remove_duplicates_from_sorted.py b/remove_duplicates_from_sorted.py new file mode 100644 index 00000000..0b5ffed9 --- /dev/null +++ b/remove_duplicates_from_sorted.py @@ -0,0 +1,27 @@ +""" +time - o(n) +space o(1) +keep two pointers (slow and fast), the slow pointer tracks the place where we copy the number and return the final size +the fast pointer keeps track of how many duplicates are there, if there are more than two, we just copy the number twice and move the +slow pointer +""" + +from typing import List + + +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + left = right = 0 + while right < len(nums): + curr = nums[right] + count = 0 + while right < len(nums) and nums[right] == curr: + count += 1 + right += 1 + if count > 2: + count = 2 + while count != 0: + nums[left] = curr + count -= 1 + left += 1 + return left diff --git a/search_2d_matrix.py b/search_2d_matrix.py new file mode 100644 index 00000000..afbb1d4d --- /dev/null +++ b/search_2d_matrix.py @@ -0,0 +1,23 @@ +""" +time - o(n) +space - o(1) +we start at the top right most element of the matrix since the rows and columsn are sorted if the number if lesser than target we go to the left +if greater we move down till we find the element or exit the matrix +""" + +from typing import List + + +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + x, y = 0, len(matrix[0]) - 1 + while 0 <= x < len(matrix) and 0 <= y < len(matrix[0]): + num = matrix[x][y] + if num == target: + return True + elif target < num: + y -= 1 + else: + x += 1 + + return False