Expedia Interview Question
Software Engineer / Developerscan solve this with the same list by using 2 index variables 1 for reading current element & progressing forward(readPos) & the other for write position. Every time before writing something at write pos, compare it with readPos
My 2 cents...
public static void removeDuplicates(int[] a1) {
int a2[] = new int[6];
int j = 0;
for (int i = 0; i < a1.length; i++) {
if (i < (a1.length - 1)) {
if (a1[i] == a1[i + 1]) {
} else {
a2[j] = a1[i];
j++;
}
} else {
if (a1[i] == a1[i - 1]) {
a2[j] = a1[i];
} else {
a2[j] = a1[i];
}
}
}
for (int i = 0; i < a2.length; i++) {
System.out.println(a2[i]);
}
}
say arr = {1, 2, 2, 3, 4, 4, 4, 5}
- Jimmy December 10, 2007we need to change it into
arr - {1, 2, 3, 4, 5}
int num = arr[0];
list.add(num);
int j = 0;
for( int i = 1; i < arr.length; i++ ) {
if( list.get(j) < arr[i] ) {
list.add(arr[i]);
j++;
}
else { // duplicate
continue;
}
}
This solves the problem with complexity O(n), but requires an extra list.