IMC Trading Interview Question

Write a function that takes in an integer array and returns a boolean, whether or not the array has duplicates in it.

Interview Answers

Anonymous

Aug 6, 2017

// Java implementation import java.util.HashMap; class ArrayDup { public static boolean hasDuplicate(int[] a) { HashMap elementFreq = new HashMap(); for(int x = 0; x < a.length; x++) { if(elementFreq.get(a[x]) == null) elementFreq.put(a[x], 1); else return true; } return false; } public static void main(String[] args) { int[] a = {0,1,3,2,3}; int[] b = {0,1,2,3}; System.out.println(hasDuplicate(a)); System.out.println(hasDuplicate(b)); } }

1

Anonymous

Jan 9, 2015

Iterate through the array, adding elements to a set. If you try to add an element already in the set, there is a duplicate. O(n)

1