# Beautiful Python Solution

• def merge(self, nums1, m, nums2, n):
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]

• A solution may be more concise:

def merge(self, nums1, m, nums2, n):
while n > 0:
if m <= 0 or nums2[n-1] >= nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1] = nums1[m-1]
m -= 1

• the answer id delicious : )

• My custom test case is :
[1,2,3]
3
[1]
1

And I got error:IndexError: list assignment index out of range.

Do you know why?

• @wx6698

Because your custom test case is wrong. The first list should have enough space for merging two lists. So you can try:
[1,2,3,0]
3
[1]
1
The last "0" is the extra space for merging. Anyway, the description of the problem is not clear. I had tried several test cases to figure it out.

• This post is deleted!

• @cffls this is indeed a beautiful solution!

• This post is deleted!

• @tju_xu97 This is great. The use of OR operator helps escape the out of index range error which busted my mind for hours. Thanks a lot.

• def merge(self, nums1, m, nums2, n):
while n > 0:
if m <= 0 or nums2[n-1] >= nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1] = nums1[m-1]
m -= 1

Why this is not working for the following ??
Input:
[0]
0
[1]
1
Output:
[0]
Expected:
[1]

for i in range(n):
nums1[m + i] = nums2[i]
nums1.sort()

• @qzhao123 great!!!

• why this code give me a ''wrong answer''??? I don't understand.
'''
for i in range(n):
nums1.append(nums2[i])

nums1.sort()
'''

• @cffls
If I change the last line into nums1 = nums[:n]
input:[0], 0, [1], 1
output: [0]
expected: [1]
But run the code in my pc that the output is [1].
don't konw the reason.

• Input:[0] 0 [1] 1
This is a wrong testcase,the length of [0] should be 1 not 0.
It should be [] 0 [1] 1 or [0] 1 [1] 1

• @cffls This is certainly an elegant solution :) Thank you for sharing!

• What if the input nums1 and nums2 are descending? Looks like it can't deal with this.
For the input below, the result is [1,3,2,1,2], which is wrong. The expected answer [3,2,1,1,2] is also wrong.

[3, 2, 1, 0, 0]
3
[1, 2]
2

• This is way easier(beats 98.5%)...

def merge(self, nums1, m, nums2, n):
nums1[m:] = nums2[:n]
nums1.sort()

Also, I believe some of you are reading the question wrong. We only use the first m numbers in nums1 and the first n numbers in nums2 for the final solution.

• @qzhao123 This is wrong, since nums1 size could be larger than m+n, so if you sort nums1 you are sorting all the elements which is not the correct

• @chch1992 input [0],0, I think the input is wrong, as '0' in [ ],it means it has 1 element,not 0.

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