Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions merge_arrays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
time - o(n)
space - o(1)
set p and q to m-1 and n-1, these are pointers that point to the biggest elements in both the lists. whichever is the biggest among the two copy them to the last position in nums1. Then decrement the corresponding pointer.
the last position of the array nums1 is tracked by the pointer r = m+n-1
"""

from typing import List


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.
"""
# edge case if m=0 or n=0
if m == 0:
nums1[0] = nums2[0]
p = m - 1
q = n - 1
r = m + n - 1
while r >= 0:
if p >= 0 and q >= 0:
if nums1[p] > nums2[q]:
nums1[r] = nums1[p]
p -= 1
else:
nums1[r] = nums2[q]
q -= 1
r -= 1
elif p >= 0:
nums1[r] = nums1[p]
r -= 1
p -= 1
elif q >= 0:
nums1[r] = nums2[q]
q -= 1
r -= 1
27 changes: 27 additions & 0 deletions remove_duplicates_from_sorted.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
time - o(n)
space o(1)
keep two pointers (slow and fast), the slow pointer tracks the place where we copy the number and return the final size
the fast pointer keeps track of how many duplicates are there, if there are more than two, we just copy the number twice and move the
slow pointer
"""

from typing import List


class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
left = right = 0
while right < len(nums):
curr = nums[right]
count = 0
while right < len(nums) and nums[right] == curr:
count += 1
right += 1
if count > 2:
count = 2
while count != 0:
nums[left] = curr
count -= 1
left += 1
return left
23 changes: 23 additions & 0 deletions search_2d_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
time - o(n)
space - o(1)
we start at the top right most element of the matrix since the rows and columsn are sorted if the number if lesser than target we go to the left
if greater we move down till we find the element or exit the matrix
"""

from typing import List


class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
x, y = 0, len(matrix[0]) - 1
while 0 <= x < len(matrix) and 0 <= y < len(matrix[0]):
num = matrix[x][y]
if num == target:
return True
elif target < num:
y -= 1
else:
x += 1

return False