Coding Interview Question: Find Duplicates

Find Duplicates: Coding Interview Question

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.

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):

// 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 findDuplicates(int[] arr) {
    // Use a set for results to avoid duplicates
    Set resultSet = new HashSet();
        
    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.

Don't do another coding interview...​

…Until you’ve mastered these 50 questions!

50 Coding Interview Questions Cover
Sam Gavis-Hughson

Sam Gavis-Hughson

Sam, founder of Byte by Byte, helps software engineers successfully interview for jobs at top tech companies. Sam has helped thousands of students through his blog and free content -- as well as 400+ paying students -- land jobs at companies such as Google, Amazon, Microsoft, Bloomberg, Uber, and more.