First Non Distinct value in an Array

Find the non-distinct value in a given array

Input : {1,1,2,2,3,4,4}

Output : 3

Code

package wordpress;

import java.util.Hashtable;

public class Nondistinct {

    private static Integer firstNonDistinct(Integer[] input) {
        Hashtable<Integer, Integer> hash = new Hashtable<>();
        for (Integer key : input) {
            if (hash.containsKey(key)) {
                int count = hash.get(key);
                hash.put(key, ++count);
            } else {
                hash.put(key, 1);
            }
        }
        for (Integer key : input) {
            if (hash.get(key) == 1)
                return key;
        }
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(firstNonDistinct(new Integer[]{1, 1, 2, 2, 3, 4, 4})); // 3
        System.out.println(firstNonDistinct(new Integer[]{1, 1, 2, 2, 3,3, 4, 4})); // 0
        System.out.println(firstNonDistinct(new Integer[]{1,2,3,4})); // 1
        System.out.println(firstNonDistinct(new Integer[]{-1,0,0,1,1})); // -1
    }
}
Scroll to Top