Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active June 10, 2020 06:15
Show Gist options
  • Select an option

  • Save manojnaidu619/96d5d496f625764d6bd733cd717a21a2 to your computer and use it in GitHub Desktop.

Select an option

Save manojnaidu619/96d5d496f625764d6bd733cd717a21a2 to your computer and use it in GitHub Desktop.
Merge two sorted arrays. (using constant space)
a = [2]
b = [-10,3]
a_pointer = len(a)-1
b_pointer = len(b)-1
for _ in range(len(b)): a.append(0)
l_pointer = len(a)-1
while(a_pointer >= 0 and b_pointer >= 0):
if(a[a_pointer] > b[b_pointer]):
a[l_pointer] = a[a_pointer]
a_pointer -= 1
l_pointer -=1
else:
a[l_pointer] = b[b_pointer]
l_pointer -= 1
b_pointer -= 1
if(a_pointer < 0 and b_pointer>=0):
while(l_pointer>=0):
a[l_pointer] = b[b_pointer]
l_pointer -=1
b_pointer-=1
print(a)
# time complexity = O(m+n)
# Space complexity = O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment