Question
Given an array of integers where each value 1 <= x <= len(array)
, write a function that finds all the duplicates in the array.
eg.
1 2 3 4 |
dups([1, 2, 3]) = [] dups([1, 2, 2]) = [2] dups([3, 3, 3]) = [3] dups([2, 1, 2, 1]) = [1, 2] |
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video (Github):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Return a list of duplicates in the array. To avoid using extra space, // we flag which elements we've seen before by negating the value at // indexed at that value in the array. public static List<Integer> findDuplicates(int[] arr) { // Use a set for results to avoid duplicates Set<Integer> resultSet = new HashSet<Integer>(); for (int i = 0; i < arr.length; i++) { // Translate the value into an index (1 <= x <= len(arr)) int index = Math.abs(arr[i]) - 1; // If the value at that index is negative, then we've already seen // that value so it's a duplicate. Otherwise, negate the value at // that index so we know we've seen it if (arr[index] < 0) { resultSet.add(Math.abs(arr[i])); } else { arr[index] = -arr[index]; } } // Return the array to it's original state for (int i = 0; i < arr.length; i++) { arr[i] = Math.abs(arr[i]); } return new ArrayList(resultSet); } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.