During a recent interview, I was asked the following question and despite being able to solve it, the interviewer pointed out that my code was not optimized. Is there anyone who can help me with an optimized solution?
Question : Given an array array1, rearrange the array in the format:
- All negative numbers and their absolute values should be inserted first in the array (sorted).
- The remaining items should be concatenated 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 has a time complexity of o(n^2), but the interviewer wanted a O(log n) solution without nested for loops. Can we achieve this?