This was my interview question, and I am able to solve it, But left with a note from interviewer, saying this is not optimized code, I am not able to solve it in optimized solution, any one here to help.
Question : Given an array array1, rearrange the array in the format
- all negative and its absolue number to be inserted first in the array (Sorted).
- and all the remaning items should be concated to the new array (Sorted)
//input
var array = [8,7,0,6,4,-9,-7,2,-1,3,5,1,10];
//output
var array2 = [-7,7,-1,1,-9,0,2,3,4,5,6,8,10];
My Code :
function sort(arr){
var arrange = arr.sort((a, b)=>{ return a-b});
var array1=[];
for(let i=0; i<arrange.length; i++){
let firstItem = Math.abs(arrange[i]);
for(let j=i+1; j<arrange.length; j++){
if(firstItem === Math.abs(arrange[j])){
array1.push(arrange[i], arrange[j])
}
}
}
arrange = arrange.filter((item, i)=>{
return array1.indexOf(item) === -1
})
return [...array1, ...arrange]
}
console.log(sort(array));
Please give some hints also, what is wrong with my approach.
Note : The code I wrote is like o(n^2),, he wanted a O(log n), he meant , Without nested for loops , we can solve it. can we ?