educative.io

I am not getting proper sorted list

I tried with array [1,2,3,4] and [2,7,6,8] but getting the result [1,2,2,3,4,7,6,8]. Here 7,6 are not sorted properly using both solutions.

Good question, you have a sharp sight! I am your mate who enjoy learning this as well, hope my explanation can help you! :grinning:

For solution 1, the idea is to creat a new list (its name called result) to store the elements from two lists. So no doubt its extra space spent is O(m+n) after assuming input is O(n) (for lst1 length) and O(m) (for lst2 length) respectively.
And why it cannot getting proper sorted list?

It relates two reasons.
As you can see, in the first while loop, it is the comparison between the lst1’s arr1 size & lst2’s arr2 size. So it’s only a 1 vs 1 comparison. Once you got a smaller element in 1 vs 1 comparison, the smaller element will add in the new list, and this smaller element no long participate in the comparison again. Therefore,we can get the first reason that the order of the ultimate elements are related to the appearance of the elements in their original lists.

And what’s the usage for the next two while loop? Their exist is to assure the remaining elements in another list (e.g. lst2) can be added to the new list (named result) after the elements in one list (e.g. lst1) have all been sorted (added in new list already). In other words, the elements left in one list haven’t been compared would directly add in the new list (result).

For solution 2, same theory as above. The only difference is that it is smart to use list. insert function instead of creating a new list. The action itself saves the extra space, and reduced it to O(m) (assuming all the elements in lst2 are larger than elements in Original lst1, in result adding all the elements in lst2 into lst1.)

Best,
Yan

@Al_Momin_Faruk you don’t get a correct result because you passed a list that is not sorted ([2,7,6,8]). this question/solutions assume lst1 and lst2 are sorted.