Skip to content
Open

done #1739

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
21 changes: 21 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
we use two pointers, i and left, such that i traverses the array an slow pointer remains on the last valid element, and later replaces another valid
element found in future. TC is o(n) and sc is o(1)"""

class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
slow = 1
count = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
count += 1
else:
count = 1
if count <= 2:
nums[slow] = nums[i] #overwrite the number we want to keep at the slow pointer
slow += 1
return slow
35 changes: 35 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
We use two pointers from the end of the lists and maintain a last pointer as a third one to swap the elements greater than one at m and n position to the last
place of the nums1 array. The remaining elements, if any are placed in the last element as a loop
TC is o(m+n) and SC is o(!)"""


class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
last = m + n - 1
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
nums1[last] = nums1[m - 1]
m -= 1
else:
nums1[last] = nums2[n - 1]
n -= 1
last -= 1

#if there are still elements left in the nums 2 array
while n > 0:
nums1[last] = nums2[n-1]
n -= 1
last -= 1





27 changes: 27 additions & 0 deletions problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
we use boundary condtions and check that if we move left and down as two options, we can reach the answer in o(m+n) time, hence we traverse the array in such
way that we move left and down
TC is o(m+n) and SC is o(1)"""


class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix) #rows
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