diff --git a/dupinsortedarr.py b/dupinsortedarr.py new file mode 100644 index 00000000..9dda0fe0 --- /dev/null +++ b/dupinsortedarr.py @@ -0,0 +1,17 @@ +class Solution: + def removeDuplicates(self, nums): + if len(nums) <= 2: + return len(nums) + + i = 2 + + # If you want each number at most k times: Keep nums[j] != nums[i-k] + for j in range(2, len(nums)): + if nums[j] != nums[i - 2]: + nums[i] = nums[j] + i += 1 + + return i +# using slow and fast pointers (i and j) +# TC - O(n) +# SC - O(1) \ No newline at end of file diff --git a/mergesortedarr.py b/mergesortedarr.py new file mode 100644 index 00000000..d52007da --- /dev/null +++ b/mergesortedarr.py @@ -0,0 +1,25 @@ +class Solution: + def merge(self, nums1, m, nums2, n): + i = m - 1 + j = n - 1 + k = m + n - 1 + + while i >= 0 and j >= 0: + + if nums1[i] > nums2[j]: + nums1[k] = nums1[i] + i -= 1 + else: + nums1[k] = nums2[j] + j -= 1 + + k -= 1 + + # If nums2 still has elements + while j >= 0: + nums1[k] = nums2[j] + j -= 1 + k -= 1 + +# TC - O(m+n) +# SC - O(1) \ No newline at end of file diff --git a/search2dmat.py b/search2dmat.py new file mode 100644 index 00000000..d2327454 --- /dev/null +++ b/search2dmat.py @@ -0,0 +1,19 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m = len(matrix) + 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 + +# TC - O(m+n) Each move eliminates one row or one column +# SC - O(1) \ No newline at end of file