Hardik Chauhan
BAN USER
Comments (3)
Reputation 0
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
let array = [1,6,9,4,10,9,8,8,4];
function positiveNegativeArray(originalArray){
let positiveArray = [];
for(let i of originalArray){
if(i > 0) positiveArray.push(i);
}
let negativeArray = [];
for(let i of originalArray){
if(i < 0) negativeArray.push(i);
}
let pos = 0, neg = 0;
for(let i=0; i < originalArray.length; i++){
if(positiveArray && pos > positiveArray.length  1) positiveArray = null;
if(negativeArray && neg > negativeArray.length  1) negativeArray = null;
if((i % 2 === 0  !negativeArray) && positiveArray){
originalArray[i] = positiveArray[pos];
++pos;
}else{
originalArray[i] = negativeArray[neg];
++neg;
}
}
return originalArray;
}
positiveNegativeArray(array);

Hardik Chauhan
February 22, 2020 Comment hidden because of low score. Click to expand.
0
of 0 vote
If the question says that the difference has to be absolute, then sorting the array and finding the adjacent difference is the most appropriate solution. But if the question says finding the smallest difference out of all the pairs from an array i.e min_diff can be less than 0, then we can find it with the following code.
MIN_DIFF(ARRAY){
MAX_ELEMENT := FIND_MAX(ARRAY) //O(n)
MIN_ELEMENT := FIND_MIN(ARRAY) //O(n)
return MIN_ELEMENT  MAX_ELEMENT
}
This this runs in O(n) time and O(1) space.
 Hardik Chauhan February 22, 2020Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
 Hardik Chauhan February 24, 2020