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
32 changes: 32 additions & 0 deletions merge-sorted-array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
''' Time Complexity : O(n)
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No


Approach : Maintain 2 pointers from end of array, and one right pointer at end of 1st array
swap the largest element at end of array and move the right pointer inside
'''

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
r = (m+n)-1
print(p1,p2,r)
while p1 >= 0 and p2 >= 0:
if nums1[p1] >= nums2[p2]:
nums1[r] = nums1[p1]
r -= 1
p1 -= 1
else:
nums1[r] = nums2[p2]
r -= 1
p2 -= 1
while p2 >= 0:
nums1[r] = nums2[p2]
r -= 1
p2 -= 1
30 changes: 30 additions & 0 deletions remove-duplicates-from-sorted-array-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
''' Time Complexity : O(2n)
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No


Approach : Maintain two pointers, one to overwirte and one to scan, update the array where count <= k
'''
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k = 2
p1 = 0
i = 0
count = 0
while i < len(nums):
if i != 0 and nums[i] == nums[i-1]:
count += 1
else:
count = 1

if count <= k:
nums[p1] = nums[i]
p1 += 1

i += 1
return p1




20 changes: 20 additions & 0 deletions search-a-2d-matrix-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
''' Time Complexity : O(m+n)
Space Complexity : O(1)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No


Approach : Start from Top-Right corner, if target is less then go to left, else go to downwards
'''
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
rows,cols = len(matrix), len(matrix[0])
r, c = 0, cols-1
while 0<=r<rows and 0<=c<cols:
if target == matrix[r][c]:
return True
elif target < matrix[r][c]:
c -= 1
else:
r += 1
return False