Skip to content

Instantly share code, notes, and snippets.

@gbhasha
Created May 3, 2018 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbhasha/c27d73a67202af0e70d41922d8453f9f to your computer and use it in GitHub Desktop.
Save gbhasha/c27d73a67202af0e70d41922d8453f9f to your computer and use it in GitHub Desktop.
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.…
function firstDuplicate (numArray) {
const len = numArray.length;
let result = -1;
if(len < 2) {
return result
}
let dupArray=[];
let lenFirst;
if( len % 2 === 0 ) {
lenFirst = len /2
}
else {
lenFirst = (len-1) / 2;
}
let firstArray = numArray.slice(0, lenFirst);
let secondArray = numArray.slice(lenFirst, len);
for(let i = 0; i < firstArray.length; i++) {
for(let j = i+1; j < firstArray.length; j++) {
if(firstArray[i] == firstArray[j]) {
dupArray.push(j);
break;
}
}
}
for(let i = 0; i < secondArray.length; i++) {
for(let j = i+1; j < secondArray.length; j++) {
if(secondArray[i] == secondArray[j]) {
dupArray.push(lenFirst + j);
break;
}
}
}
for(let i = 0; i < numArray.length; i++) {
for(let j = i+1; j < numArray.length; j++) {
if(numArray[i] == numArray[j]) {
dupArray.push(j);
break;
}
}
}
if(dupArray.length > 1) {
result = numArray[Math.min.apply(null, dupArray)];
} else {
result = numArray[dupArray[0]] || -1;
}
return result;
}
@gbhasha
Copy link
Author

gbhasha commented May 3, 2018

Example

For a = [2, 3, 3, 1, 5, 2], the output should be
firstDuplicate(a) = 3.

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.

For a = [2, 4, 3, 5, 1], the output should be
firstDuplicate(a) = -1.

Input/Output

[execution time limit] 4 seconds (js)

[input] array.integer a

Guaranteed constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.

[output] integer

The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1.

@gbhasha
Copy link
Author

gbhasha commented May 3, 2018

Shorter version and less time complexity:

firstDuplicate = a => {
    r = new Set()
    
    for (e of a) 
    if (r.has(e))
    return e
    else
    r.add(e)
    return -1
}

@gbhasha
Copy link
Author

gbhasha commented May 3, 2018

Shorter version without using Set:

firstDuplicate = a => {
    r = [];
    for(e of a) 
    if(r.indexOf(e) > -1) 
    return e
    else
    r.push(e)
    return -1
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment