Google Interview Question

Remove the duplicates from an array in place

Interview Answers

Anonymous

Jan 31, 2015

sort the array. then take two pointers, slow and fast. fast will scan for duplicate values in front of slow and whenever a duplicate is detected. it skips that. non duplicated values are preserved, duplicates are overwritten.

2

Anonymous

Feb 2, 2015

public static void removeDuplicates(int[] nums) { if(nums == null || nums.length < 2) return; Arrays.sort(nums); int last = nums[0]; int pos = 1; int look = 1; while(look < nums.length) { if(nums[look] != last) { nums[pos] = nums[look]; pos++; last = nums[look]; } look++; } // setting rest of array values to 0 while(pos < nums.length) nums[pos++] = 0; }

Anonymous

Feb 12, 2015

public static void removeDuplicate(int[] a){ if(a == null || a.length < 2){ return; } Arrays.sort(a); int slow = 0; int fast = 0; while(fast < a.length){ if(a[slow] != a[fast]){ slow++; a[slow] = a[fast]; } fast++; } return; }

1

Anonymous

Feb 11, 2015

// remove duplicate public static void removeDuplicate(int[] array, int x) { Arrays.sort(array); int duplicateLength = 0; for (int i = array.length - 2; i >= 0; i--) { if (array[i + 1] == array[i]) { // send it to the end of the array swap(array, i + 1, array.length - duplicateLength - 1); duplicateLength++; } } for (int i = 0; i < duplicateLength; i++) { array[array.length - duplicateLength + i] = x; } } private static void swap(int[] array, int index1, int index2) { int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; }