From 48dc2621776d7ec49dbf31f9eeb9ad44246ab77d Mon Sep 17 00:00:00 2001 From: Vaishnavi Gawale Date: Fri, 9 Jan 2026 15:58:45 -0500 Subject: [PATCH] Done Two-Pointers-2 --- merge-sorted-array.py | 32 +++++++++++++++++++++++ remove-duplicates-from-sorted-array-ii.py | 30 +++++++++++++++++++++ search-a-2d-matrix-ii.py | 20 ++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 merge-sorted-array.py create mode 100644 remove-duplicates-from-sorted-array-ii.py create mode 100644 search-a-2d-matrix-ii.py diff --git a/merge-sorted-array.py b/merge-sorted-array.py new file mode 100644 index 00000000..38b4aa5c --- /dev/null +++ b/merge-sorted-array.py @@ -0,0 +1,32 @@ +''' Time Complexity : O(n) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No + + + Approach : Maintain 2 pointers from end of array, and one right pointer at end of 1st array + swap the largest element at end of array and move the right pointer inside +''' + +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. + """ + p1 = m-1 + p2 = n-1 + r = (m+n)-1 + print(p1,p2,r) + while p1 >= 0 and p2 >= 0: + if nums1[p1] >= nums2[p2]: + nums1[r] = nums1[p1] + r -= 1 + p1 -= 1 + else: + nums1[r] = nums2[p2] + r -= 1 + p2 -= 1 + while p2 >= 0: + nums1[r] = nums2[p2] + r -= 1 + p2 -= 1 \ No newline at end of file diff --git a/remove-duplicates-from-sorted-array-ii.py b/remove-duplicates-from-sorted-array-ii.py new file mode 100644 index 00000000..6e91b31e --- /dev/null +++ b/remove-duplicates-from-sorted-array-ii.py @@ -0,0 +1,30 @@ +''' Time Complexity : O(2n) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No + + + Approach : Maintain two pointers, one to overwirte and one to scan, update the array where count <= k +''' +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + k = 2 + p1 = 0 + i = 0 + count = 0 + while i < len(nums): + if i != 0 and nums[i] == nums[i-1]: + count += 1 + else: + count = 1 + + if count <= k: + nums[p1] = nums[i] + p1 += 1 + + i += 1 + return p1 + + + + \ No newline at end of file diff --git a/search-a-2d-matrix-ii.py b/search-a-2d-matrix-ii.py new file mode 100644 index 00000000..0f76cc4b --- /dev/null +++ b/search-a-2d-matrix-ii.py @@ -0,0 +1,20 @@ +''' Time Complexity : O(m+n) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No + + + Approach : Start from Top-Right corner, if target is less then go to left, else go to downwards +''' +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + rows,cols = len(matrix), len(matrix[0]) + r, c = 0, cols-1 + while 0<=r