From f4e8d947c909dc1eb2073f8b8edfbab715739e86 Mon Sep 17 00:00:00 2001 From: amitmittal117 Date: Tue, 3 Feb 2026 19:12:00 -0800 Subject: [PATCH] [IMP] Two-Pointer-2 --- merge-sorted-array.py | 26 +++++++++++++++++++++++ remove-duplicates-from-sorted-array-ii.py | 21 ++++++++++++++++++ search-a-2d-matrix-ii.py | 14 ++++++++++++ 3 files changed, 61 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..834b2acc --- /dev/null +++ b/merge-sorted-array.py @@ -0,0 +1,26 @@ +''' +Time Complexity : O(n) +Space Complexity : O(1) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +class Solution: + def merge(self, nums1, m, nums2, n): + """ + Do not return anything, modify nums1 in-place instead. + """ + p1 = m - 1 + p2 = n - 1 + p3 = m + n - 1 + while p2 >= 0 and p1 >= 0: + if nums2[p2] >= nums1[p1]: + nums1[p3] = nums2[p2] + p2 -= 1 + else: + nums1[p3] = nums1[p1] + p1 -= 1 + p3 -= 1 + while p2 >=0: + nums1[p3] = nums2[p2] + p2 -= 1 + p3 -= 1 diff --git a/remove-duplicates-from-sorted-array-ii.py b/remove-duplicates-from-sorted-array-ii.py new file mode 100644 index 00000000..87c06ecd --- /dev/null +++ b/remove-duplicates-from-sorted-array-ii.py @@ -0,0 +1,21 @@ +''' +Time Complexity : O(n) +Space Complexity : O(1) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +class Solution: + def removeDuplicates(self, nums): + n = len(nums) + slow = 1 + count = 1 + for i in range(1, n): + if nums[i] == nums[i - 1]: + count += 1 + else: + count = 1 + if count <= 2: + nums[slow] = nums[i] + slow += 1 + return slow + \ 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..642538f8 --- /dev/null +++ b/search-a-2d-matrix-ii.py @@ -0,0 +1,14 @@ +class Solution: + def searchMatrix(self, matrix, target): + m = len(matrix) + n = len(matrix[0]) + c = 0 + r = m - 1 + while r >= 0 and c < n: + if matrix[r][c] == target: + return True + elif matrix[r][c] > target: + r -= 1 + else: + c += 1 + return False \ No newline at end of file