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
29 changes: 29 additions & 0 deletions Problem_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/

# Time complexity: O(n)
# Space complexity: O(1)
# Explanation: Maintain two points, one to check count and one to act as the current index being written to. Keep iterating the elements and then return the 2nd pointer value.

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0

i = 1
j = 1
count = 1

while i < len(nums):
if nums[i] == nums[i-1]:
count += 1
if count > 2:
i += 1
continue
else:
count = 1
nums[j] = nums[i]
j += 1
i += 1

del nums[j:]
return j + 1
23 changes: 23 additions & 0 deletions Problem_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# https://leetcode.com/problems/merge-sorted-array/description/

# TC: O(n + m)
# SP: O(1)
# Explanation: Place two points at the end of each nums array, and another pointer at the nums1;
# keep comparing nums1 vs nums2 and insert the higher value, and in the end you will get the fully sorted array in nums1

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
for p in range(n + m - 1, -1, -1):
if p2 < 0:
break
if p1 >= 0 and nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
20 changes: 20 additions & 0 deletions Problem_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# https://leetcode.com/problems/search-a-2d-matrix-ii/description/

# Time complexity: O(n)
# Space complexity: O(1)
# Explanation: Start from the bottom left. If the curr value is greater than target, shift up a row. If smaller, then shift right. Finally return target.

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
i, j = m - 1, 0

while i >=0 and j < n:
if matrix[i][j] > target:
i -= 1
elif matrix[i][j] < target:
j += 1
else:
return True

return False