First Repeat Gift

In the toy factory of the North Pole, each toy has a unique identification number.

However, due to an error in the toy machine, some numbers have been assigned to more than one toy.

Find the first identification number that has been repeated, where the second occurrence has the smallest index!

In other words, if there is more than one repeated number, you must return the number whose second occurrence appears first in the list. If there are no repeated numbers, return -1.

1const giftIds = [2, 1, 3, 5, 3, 2];
2const firstRepeatedId = findFirstRepeated(giftIds);
3console.log(firstRepeatedId); // 3
4// Aunque el 2 y el 3 se repiten
5// el 3 aparece primero por segunda vez
6
7const giftIds2 = [1, 2, 3, 4];
8const firstRepeatedId2 = findFirstRepeated(giftIds2);
9console.log(firstRepeatedId2); // -1
10// Es -1 ya que no se repite ningĂșn nĂșmero
11
12const giftIds3 = [5, 1, 5, 1];
13const firstRepeatedId3 = findFirstRepeated(giftIds3);
14console.log(firstRepeatedId3); // 5

Watch out! The elves say this is a Google technical test.

Source: AdventJS

Author: @Midudev

solution.ts
1function findFirstRepeated(gifts: number[]) {
2 const seen: { [key: number]: boolean } = {};
3
4 for (const gift of gifts) {
5 if (seen[gift]) return gift;
6 seen[gift] = true;
7 }
8
9 return -1;
10}
11
12const giftIds = [2, 1, 3, 5, 3, 2];
13const firstRepeatedId = findFirstRepeated(giftIds);
14console.log(firstRepeatedId); // 3
15// Aunque el 2 y el 3 se repiten
16// el 3 aparece primero por segunda vez
17
18const giftIds2 = [1, 2, 3, 4];
19const firstRepeatedId2 = findFirstRepeated(giftIds2);
20console.log(firstRepeatedId2); // -1
21// Es -1 ya que no se repite ningĂșn nĂșmero
22
23const giftIds3 = [5, 1, 5, 1];
24const firstRepeatedId3 = findFirstRepeated(giftIds3);
25console.log(firstRepeatedId3); // 5