How to find first non repeating number from an array | Coding Interview Problem

We are going to solve a problem about duplicate/unique number which is frequently asked in coding interviews. The problem statement is you need to output a number which is the first non repeating number (or first unique) from 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,2,2,3,3,1,2,3,5,4,3,9,0,2] - this array has four unique numbers such as 1, 5,4, and 9. We can see 1 is the number is first unique number here. Because, 2 is on index 5 and whereas others are ahead of index 5. 

In the example below, it is clear that 1 is the first non repeating number.

Input: [2,2,2,3,3,1,2,3,5,4,3,9,0,2]
Output: 1
Here is the code: 
import java.util.*;

public class firstNonRepeatingNumber {
    public static void main(String[] args) {
        int[] arr = new int[] {2,2,2,3,3,1,2,3,5,4,3,9,0,2};
        HashMap<IntegerIntegerhMap = new HashMap<>();

        for(int i: arr){
            if(hMap.containsKey(i)){
                hMap.put(i, hMap.get(i) + 1);
            } else {
                hMap.put(i, 1);
            }
        }

        for(int i: arr){
            if(hMap.get(i) == 1){
                System.out.print("Answer: "+ i);
                break;
            }
        }
        
    }
}

Here is the YouTube video:

Comments

Popular Posts