How to find first duplicate in array | Coding Interview Problem

We are going to solve a problem which is frequently asked in coding interviews. The problem statement is you need to output a number which is the first duplicate of an array.

Before, you move to the solution, it would be nice if you can try on a piece of paper and then solve by coding it. If you prefer video explanation then you can watch on YouTube (in English or in Hindi). 

Lets understand it by an example. Take an array like [2,4,6,8,2,9,8], this array has two duplicate numbers such as 2 and 8. We can see 2 is the number is first duplicate. Because, 2 is on index 0 and 4 whereas 8 is on index 3 and 6. So, we need to see whose second index is lowest among duplicates.

In the example below, it is clear that 2 is the first duplicate.
Input: [2,4,6,8,2,9,8]
Output: 2

Now, how do we solve this in coding? So, we can take help hashmap/dictionary to store count of a array element. While iterating, if we found a number exists in the hashmap/dictionary  then we found our first duplicate.

Here is the code: 




Here is the YouTube video:

Comments

Popular Posts