From d86167a0bf061682377f09009b2d3dc4e6197661 Mon Sep 17 00:00:00 2001 From: Purva Date: Sun, 30 Nov 2025 09:57:12 -0600 Subject: [PATCH] done --- problem1.py | 21 +++++++++++++++++++++ problem2.py | 35 +++++++++++++++++++++++++++++++++++ problem3.py | 27 +++++++++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 problem1.py create mode 100644 problem2.py create mode 100644 problem3.py diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..6739c498 --- /dev/null +++ b/problem1.py @@ -0,0 +1,21 @@ +""" +we use two pointers, i and left, such that i traverses the array an slow pointer remains on the last valid element, and later replaces another valid +element found in future. TC is o(n) and sc is o(1)""" + +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + slow = 1 + count = 1 + for i in range(1, len(nums)): + if nums[i] == nums[i-1]: + count += 1 + else: + count = 1 + if count <= 2: + nums[slow] = nums[i] #overwrite the number we want to keep at the slow pointer + slow += 1 + return slow \ No newline at end of file diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..b17fe50d --- /dev/null +++ b/problem2.py @@ -0,0 +1,35 @@ +""" +We use two pointers from the end of the lists and maintain a last pointer as a third one to swap the elements greater than one at m and n position to the last +place of the nums1 array. The remaining elements, if any are placed in the last element as a loop +TC is o(m+n) and SC is o(!)""" + + +class Solution(object): + def merge(self, nums1, m, nums2, n): + """ + :type nums1: List[int] + :type m: int + :type nums2: List[int] + :type n: int + :rtype: None Do not return anything, modify nums1 in-place instead. + """ + last = m + n - 1 + while m > 0 and n > 0: + if nums1[m - 1] > nums2[n - 1]: + nums1[last] = nums1[m - 1] + m -= 1 + else: + nums1[last] = nums2[n - 1] + n -= 1 + last -= 1 + + #if there are still elements left in the nums 2 array + while n > 0: + nums1[last] = nums2[n-1] + n -= 1 + last -= 1 + + + + + \ No newline at end of file diff --git a/problem3.py b/problem3.py new file mode 100644 index 00000000..dcdfb3c1 --- /dev/null +++ b/problem3.py @@ -0,0 +1,27 @@ +""" +we use boundary condtions and check that if we move left and down as two options, we can reach the answer in o(m+n) time, hence we traverse the array in such +way that we move left and down +TC is o(m+n) and SC is o(1)""" + + +class Solution(object): + def searchMatrix(self, matrix, target): + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + """ + m = len(matrix) #rows + n = len(matrix[0]) + r, c = 0, n - 1 + while r < m and c >= 0: + if matrix[r][c] == target: + return True + elif matrix[r][c] > target: + c -= 1 + else: + r += 1 + return False + + +