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
37 changes: 37 additions & 0 deletions merge-sorted-array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Assign pointer P1 to m-1, p2 to n-1 and p3 to m+n-1. While P1 and P2>=0 check max
# between the element at nums1[p1] and nums2[p2] and update nums1[p3] with the max value.
# decrement P3 and P1 or P2 depending on which was max. After the loop terminates,
# check if P2>=0. If it is, copy all the elelemts at nums2 from 0 to p2 to nums1 at 0 to p2.

# Time complexity: O(m+n)
# Space complexity: O(1)



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.
"""

p1=m-1
p2=n-1
p3=m+n-1

while p2>=0 and p1>=0:
if nums1[p1]>=nums2[p2]:
nums1[p3]=nums1[p1]
p1-=1
else:
nums1[p3]=nums2[p2]
p2-=1
p3-=1
# print(nums1, p2, nums2)
if p2>=0:
for i in range(p2+1):
nums1[i]=nums2[i]

30 changes: 30 additions & 0 deletions remove-duplicates-from-array-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Assign a slow pointer as 0 and count as 1. Loop through nums from index 1 and
# check if nums[i]==nums[i-1]. If they are increment the counter. Else reset the counter to 1
# if the counter is <= 2 increment slow and copy the value at i to slow. Return slow+1

# Time complexity: O(n)
# Space complexity: O(1)


class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

slow=0
count=1
n=len(nums)
for i in range(1,n):
if nums[i]==nums[i-1]:
count+=1
else:
count=1
if count<=2:
slow+=1
nums[slow]=nums[i]

return slow+1


30 changes: 30 additions & 0 deletions search-2D-matric-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Take r=0 and c=no. of columns-1. While r and c is in range of rows and columns,
# check if the elelmt at [r][c] is the target. if so, return true. If the element
# is greater than target, move left else move down.

# Time complexity: O(r+c)
# Space complexity: O(1)

class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
row=len(matrix)
col=len(matrix[0])

r=0
c=col-1

while r>=0 and r<=row-1 and c>=0 and c<=col-1:
if matrix[r][c]==target:
return True
if matrix[r][c]<target:
r+=1
elif matrix[r][c]>target:
c-=1
return False