~/problems / Arrays & hashing / Hash maps and counting

Contains Duplicate

easy ~10 min

A stadium gate logs the ID of every ticket it scans, in order. A ticket is only valid once, so if the same ID shows up twice, somebody got in on a copied ticket.

Write scanned_twice(tickets) -> bool that returns True if any ID appears more than once in tickets, and False if every ID is different.

scanned_twice([804, 17, 3302, 17, 55])   # True   (17 appears twice)
scanned_twice([9, 1, 42])                # False
scanned_twice([])                        # False

Constraints:

  • 0 <= len(tickets) <= 2 * 10^5
  • IDs are integers in [0, 10^12].

Comparing every pair of scans is O(n²), far too slow for 200,000 scans. Aim for O(n) time.

Show hint

Walk the log once and remember every ID you've already met, in a structure that answers "have I seen this before?" in O(1).

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc