title: find the first duplicate element in an array having the minimal index
body: <p>I have an array containing some duplicate elements like this :</p>
  
  <p>find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1</p>
  
  <p>For a = [2, 1, 3, 5, 3, 2], the output should be
  firstDuplicate(a) = 3.</p>
  
  <p>There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3.</p>
  
  <p>I tried this :</p>
  
  <pre><code>int firstDuplicate(int[] a) {
    Set&lt;Integer&gt; set = new HashSet&lt;&gt;();
    Map&lt;Integer, Integer&gt; hm = new HashMap&lt;Integer,Integer&gt;();
    Map.Entry&lt;Integer, Integer&gt; min = null;
    for(int i=0;i&lt;a.length;i++){
         // if(!hm.containsKey(a[i]))
                hm.put(a[i],i);
    }
    for(Map.Entry&lt;Integer,Integer&gt; entry : hm.entrySet()){
          if(min == null || entry.getValue() &lt; min.getValue()){
                min = entry;
          }
    }
    return min == null ? new Integer(-1) : min.getKey();
  </code></pre>
  
  <p>}</p>
  
  <p>It's not working out, but I got another solution online which is like this :</p>
  
  <pre><code>int firstDuplicate(int[] a) {
    Set&lt;Integer&gt; set = new HashSet&lt;&gt;();
    Map&lt;Integer, Integer&gt; hm = new HashMap&lt;Integer,Integer&gt;();
    Map.Entry&lt;Integer, Integer&gt; min = null;
    for(int i=0;i&lt;a.length;i++){
          if(set.add(a[i])==false &amp;&amp; !hm.containsKey(a[i]))
                hm.put(a[i],i);
    }
    for(Map.Entry&lt;Integer,Integer&gt; entry : hm.entrySet()){
          if(min == null || entry.getValue() &lt; min.getValue()){
                min = entry;
          }
    }
    return min == null ? new Integer(-1) : min.getKey();
  </code></pre>
  
  <p>}</p>
  
  <p>Can anyone please explain me the use of Hashset here, as it doesn't allow the duplicates so how that if condition will be workable. </p>