educative.io

Educative

Why my solution fails and what is its run time

Hi,

My solution for merging two sorted arrays is as below.

function mergeArrays(arr1, arr2) {
var newArray= [];
for(let i of arr1){
newArray.push(i)
}
for(let i of arr2){
newArray.push(i)
}
newArray.sort();
return newArray;
}
console.log(mergeArrays([1,3,4,5],[-2,2,6,7,8]))

this algorithm gives me the desired output:

 [-2,1,2,3,4,5,6,7,8]

But then why this algorithm fails one test case?

Also, please tell me what would be the run time of this algorithm.

Thanks.

Hi Neha,

This is Alina from Educative. Thank you for reaching out to us and giving your feedback.

Your algorithm fails on the following test case:

mergeArrays([-133,-100,0,4],[-2000,2000])

where the output according to your code is:

[ -100, -133, -2000, 0, 2000, 4 ]

This means that the sort method is not sorting the negative numbers correctly.
You can have a look at the use of sort method in Solution #1 in this lesson.

The time complexity for this solution will be O(nlogn) since you are using the .sort() function.

Again, thank you for your valuable feedback! If you have any further concerns/questions/comments, please let us know.
Best Regards,
Alina Fatima | Developer Advocate

It is because sort method order by lexical order if you do not pass a custom callback.

So this line
newArray.sort();
Should be
newArray.sort( (a,b) => a - b) which will return newArray in ascending order.