Why my solution fails and what is its run time


My solution for merging two sorted arrays is as below.

function mergeArrays(arr1, arr2) {
var newArray= [];
for(let i of arr1){
for(let i of arr2){
return newArray;

this algorithm gives me the desired output:


But then why this algorithm fails one test case?

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


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:


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
Should be
newArray.sort( (a,b) => a - b) which will return newArray in ascending order.