0

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.

My Code:

def firstDuplicate(a):
  seen = set()
  for i in a:
      if i in seen:
          seen.add(i)
  return(-1)
peteripp
  • 11
  • 1
  • Does this answer your question? [Find the first duplicate number for which the second occurrence has the minimal index](https://stackoverflow.com/questions/45114203/find-the-first-duplicate-number-for-which-the-second-occurrence-has-the-minimal) – TYeung Aug 21 '21 at 13:52

3 Answers3

0
def firstDuplicate(s):
    seen = {}
    for i in range(len(a)):
        if a[i] in seen:
           return a[i]
        else: 
           seen[a[i]] = a[i]
    
    return(-1)
peteripp
  • 11
  • 1
0

Solutions in Javascript

function solution(a) {    
    const duplicates = [];
    for (const i of a) {
        if (duplicates.includes(i))
            return i;
        else
            duplicates.push(i);
    }
    
    return -1;
}

console.log(solution([2, 1, 3, 5, 3, 2])); // 3
console.log(solution([2, 2])); // 2
console.log(solution([2, 4, 3, 5, 1])); // -1

function solution(a) {    
    return a.filter((n, i) => a.indexOf(n) !== i)[0] || -1;
}

console.log(solution([2, 1, 3, 5, 3, 2])); // 3
console.log(solution([2, 2])); // 2
console.log(solution([2, 4, 3, 5, 1])); // -1

function solution(a) {
    for (let i = 0; i < a.length; i++)
        if (a.indexOf(a[i]) !== i)
            return a[i];

    return -1;
}

console.log(solution([2, 1, 3, 5, 3, 2])); // 3
console.log(solution([2, 2])); // 2
console.log(solution([2, 4, 3, 5, 1])); // -1

function solution(a) {
    let i = -1;
    while (++i < a.length)
        if (a.indexOf(a[i]) !== i)
            return a[i];

    return -1;
}

console.log(solution([2, 1, 3, 5, 3, 2])); // 3
console.log(solution([2, 2])); // 2
console.log(solution([2, 4, 3, 5, 1])); // -1
0
function solution(a) {
  for (i=0; i<a.length; i++) {
    let n=a[i];
    if (a[Math.abs(n)-1]>0) {
      a[Math.abs(n)-1]= -1*a[Math.abs(n)-1]    
    } else {
      return Math.abs(n);
    }
  }
  return -1
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31