Skip to content

Commit

Permalink
updated: fixed edge cases. -@iamserda
Browse files Browse the repository at this point in the history
  • Loading branch information
iamserda committed Feb 14, 2025
1 parent 2432935 commit ae06f9c
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 deletions neetcodeio/merge_sorted_arrays.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,43 @@
def merge_sorted_arrays(arr1, arr2):
if not arr1 and not arr2:
return []
if not arr1:
return arr2
if not arr2:
return arr1

arr3 = []
ptr1 = 0
ptr2 = 0
while ptr1 < len(arr1) or ptr2 < len(arr2):
if ptr1 >= len(arr1) or arr1[ptr1] >= arr2[ptr2]:
arr3.append(arr2[ptr2])
ptr2 += 1
index1 = 0
index2 = 0
while index1 < len(arr1) or index2 < len(arr2):
if index1 >= len(arr1):
arr3.append(arr2[index2])
index2 += 1
continue
if index2 >= len(arr2):
arr3.append(arr1[index1])
index1 += 1
continue
if arr1[index1] <= arr2[index2]:
arr3.append(arr1[index1])
index1 += 1
continue
if ptr2 >= len(arr2) or arr1[ptr1] <= arr2[ptr2]:
arr3.append(arr1[ptr1])
ptr1 += 1
if arr1[index1] >= arr2[index2]:
arr3.append(arr2[index2])
index2 += 1
continue
break

return arr3


arr1 = [1, 3, 5, 7]
arr2 = [0, 2, 4, 5, 7, 8]
arr3 = merge_sorted_arrays(arr1, arr2)
print(arr3)
assert arr3 == sorted([*arr1, *arr2])
# print(arr3)
# assert arr3 == sorted([*arr1, *arr2])

arr1 = [1]
arr2 = [0]
arr3 = merge_sorted_arrays(arr1, arr2)
# print(arr3)
# assert arr3 == sorted([*arr1, *arr2])

0 comments on commit ae06f9c

Please sign in to comment.