First Badge Scanned Twice

Easy · Arrays & Hashing · about 10 min

An office door logs the badge number of every person who walks in, in the order they arrive. Badge numbers are whole numbers, 0 or more.

Security wants the first moment someone comes in for a second time. Walk the log from the start and return the badge number whose second scan comes earliest. If no badge appears twice, return -1.

  • scans has 0 to 100,000 numbers.
  • Badges can appear more than twice; only the earliest second scan matters.

Examples:

first_repeat_badge([7, 3, 9, 3, 7]) → 3 (badge 3 is scanned again at position 3, before badge 7 is scanned again at position 4)

first_repeat_badge([1, 2, 3]) → -1

Hints

  • You only need to remember which badges you have already met, not how many times.
  • Keep a set. For each scan, check the set first, then add the badge.
  • The first badge that is already in the set is the answer.

Learn the pattern first: the Arrays & Hashing lesson.

More Arrays & Hashing problems