title: Speeding up this code for codefighters javascript firstDuplicate() function
body: <p>Per Codefighters: </p>
  
  <blockquote>
    <p>Note: Write a solution with O(n) time complexity and O(1) additional
    space complexity, since this is what you would be asked to do during a
    real interview.</p>
    
    <p>Given an array a that contains only numbers in the range from 1 to
    a.length, 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>Example</p>
    
    <p>For a = [2, 3, 3, 1, 5, 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 than second occurrence of 2 does, so the
    answer is 3.</p>
    
    <p>For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1.</p>
  </blockquote>
  
  <hr>
  
  <p>So here is what I came up with. It works but fails on the final test because it ran over 4000ms. I'm at a loss as to what else I can do. Any Ideas to improve speed?</p>
  
  <pre><code>function firstDuplicate(a) {
      var test   = [],
          lowest = undefined;
  
      for (var i=0; i&lt;a.length; i++) {
          if (test.indexOf(a[i]) &gt; -1) {
              lowest = lowest || i;
              if (i &lt; lowest) {
                  lowest = i;
              }
          }
          else {
              test.push(a[i]);
          }
      }
  
      return lowest ? a[lowest] : -1;
  }
  </code></pre>
  
  <hr>
  
  <p>Here was my second attempt but still failing on the last test...</p>
  
  <pre><code>function firstDuplicate(a) {
      var low = undefined,
          last = -1;
  
      for (var i=0; i&lt;a.length; i++) {
          last = a.lastIndexOf(a[i])
          if (last &gt; i &amp;&amp; (low === undefined || last &lt; low)) {
              low = last;
          }
      }
  
      return low !== undefined ? a[low] : -1;
  }
  </code></pre>