diff --git a/merge-sorted-array.py b/merge-sorted-array.py new file mode 100644 index 00000000..3a620c4d --- /dev/null +++ b/merge-sorted-array.py @@ -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] + diff --git a/remove-duplicates-from-array-2.py b/remove-duplicates-from-array-2.py new file mode 100644 index 00000000..188b707e --- /dev/null +++ b/remove-duplicates-from-array-2.py @@ -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 + + diff --git a/search-2D-matric-2.py b/search-2D-matric-2.py new file mode 100644 index 00000000..99364913 --- /dev/null +++ b/search-2D-matric-2.py @@ -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: + c-=1 + return False + + \ No newline at end of file