• ``````def merge(self, A, m, B, n):
index = m+n-1
while index >= 0:
if m <= 0:
A[index] = B[-n]
n-=1
elif n <= 0:
break
elif A[m-1] < B[n-1]:
A[index] = B[-n]
n-=1
else:
A[index] = A[-m]
m-=1
index -=1
``````

OJ said input: [2],[1] output: [1,0]. Could someone please help me figure out where was wrong? Thanks a lot!!

• It looks like there is some misunderstanding of negative index in python.

``````def merge(self, A, m, B, n):
index = m+n-1
while index >= 0:
if m <= 0:
A[index] = B[n-1]  # A[index] = B[-n]
n-=1
elif n <= 0:
break
elif A[m-1] < B[n-1]:
A[index] = B[n-1] #  A[index] = B[-n]
n-=1
else:
A[index] = A[m-1] #  A[index] = A[-m]
m-=1
index -=1 ``````

• Thanks, Shangrila! It's working!
Do you mind I ask two more questions: #1 Why the first two condition is m<=0 and n<=0, not m=0, n=0. I was thinking about m and n are length of A and B, so it cannot be negative. #2 Why we are doing backwards order for this question? What's wrong with forward order? Thanks so much!!

1. I changed to `if m == 0:` and `elif n == 0:`, it is still working. Are you confused with `=` and `==` ?

2. Oh, I understand now. You were doing forward. It does really prove that elaborating thoughts is necessary while pasting code. Anyway, forward won't work in this case. Since the elements of B might overwrite the original element of A in the same position.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.