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.
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
Post a Comment