From 68501748aeae0048a6a366fd76d2973d0359afb6 Mon Sep 17 00:00:00 2001 From: spencerkrebs Date: Sat, 25 Apr 2026 14:54:56 -0400 Subject: [PATCH] tp2 --- merge-sorted-array.py | 25 +++++++++++++++++++++++++ remove-dups.py | 19 +++++++++++++++++++ search-2d-matrix-ii.py | 18 ++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 merge-sorted-array.py create mode 100644 remove-dups.py create mode 100644 search-2d-matrix-ii.py diff --git a/merge-sorted-array.py b/merge-sorted-array.py new file mode 100644 index 00000000..10a1ce4d --- /dev/null +++ b/merge-sorted-array.py @@ -0,0 +1,25 @@ +# O(n) time, O(1) space +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + + p1 = m-1 + p2 = n-1 + + idx = m+n-1 + + while p1 >= 0 and p2 >= 0: + + if nums1[p1] >= nums2[p2]: + nums1[idx]=nums1[p1] + p1-=1 + else: + nums1[idx]=nums2[p2] + p2-=1 + idx-=1 + + while p2>=0: + nums1[idx]=nums2[p2] + p2-=1 + idx-=1 + + return nums1 \ No newline at end of file diff --git a/remove-dups.py b/remove-dups.py new file mode 100644 index 00000000..905742de --- /dev/null +++ b/remove-dups.py @@ -0,0 +1,19 @@ +# O(n) time, O(1) space +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + + cnt = 1 + slow = 1 + k=2 + + for fast in range(1,len(nums)): + if nums[fast] == nums[fast-1]: + cnt+=1 + else: + cnt=1 + + if cnt <= k: + nums[slow]=nums[fast] + slow+=1 + + return slow \ No newline at end of file diff --git a/search-2d-matrix-ii.py b/search-2d-matrix-ii.py new file mode 100644 index 00000000..9d53496b --- /dev/null +++ b/search-2d-matrix-ii.py @@ -0,0 +1,18 @@ +# O(n+m) time, O(1) space +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m = len(matrix) + n = len(matrix[0]) + + i=0 # rows + j = n-1 # cols + + while i < m and j >= 0: + if matrix[i][j]==target: + return True + elif matrix[i][j]