Amazon Interview Question
Software Engineer in TestsTeam: Chennai
Country: India
Interview Type: Phone Interview
// int[] input = {4,5,6,6,6,6,5,4,4,6}
public static void sortArray(int[] input)
{
int start=0;
int end = input.length-1;
int counter_4 = 0;
int counter_6 = input.length-1;
while(input[counter_4]==4)
{
counter_4++;
start++;
}
while(input[counter_6]==6)
{
counter_6--;
end --;
}
while(start <end) {
if(input[start]==4 && start > counter_4)
{
int tmp = input[counter_4];
input[counter_4] = input[start];
input[start] = tmp;
counter_4++;
if(tmp!=4 && tmp!=6)
start++;
}
else if(input[start] == 6 && start<counter_6)
{
int tmp = input[counter_6];
input[counter_6] = input[start];
input[start] = tmp;
counter_6--;
if(tmp!=4 && tmp!=6)
start++;
}
else
start++;
}
System.out.println("Printing sorted array ");
for (int i = 0; i < input.length; i++) {
System.out.print(input[i]+" ");
}
System.out.println();
}
Actually none of the above ! waste of time guys, all same answers but no out of box thinking.
If you see input, the numbers are out of order at most by 4 numbers.
so what to do : build heap of 4 numbers, remove min and keep advancing after 5th number and adding new number. At the end when all numbers exhaust, add all remaining numbers on heap one by one by deleting min.
This is what the interviewer is expecting.
dutch national flag algorithm? , in place sorting, O(n) complexity.
- anonymous January 08, 2014