Double-Scanned Tickets
You run the door at a small concert. The scanner logs each ticket code it reads, in the order people walk in. Each ticket is good for one entry, so a code that shows up twice means someone copied a ticket. After the doors close, you want to know whether that happened tonight.
Your task
Write hasRepeat(codes). Return true if any code appears in the log two or more times, and false if every code is different.
An empty log has no repeats, so return false.
hasRepeat(codes: int[]) → bool
Examples
codes = [4021, 7788, 1290, 7788, 5003]
true
Code 7788 was scanned at positions 1 and 3. One repeat is enough, so the answer is true.
codes = [310, 52, 9001, 47]
false
Four scans, four different codes. Nobody got in twice.
codes = [88, 15, 42, 88]
true
The repeat need not be next to the original: here it came in three people later.
Constraints
- 0 ≤ codes.length ≤ 100,000
- 0 ≤ codes[i] ≤ 1,000,000,000
Start with brute force
Comparing every scan with every later scan takes about n²/2 comparisons, around 5 billion for 100,000 scans. Sorting and comparing neighbours is O(n log n), but still does more work than needed and reorders the log.
Hints
0 of 4 shown- Hint 1
Look at the first example. When the scanner reads the second 7788, what does it need to remember to raise the alarm?
- Hint 2
You only need one fact about each earlier code: has it been seen? You do not need to know where it appeared or how many times.
- Hint 3
Which structure answers "is this value already in my collection?" in one step?
- Hint 4
Walk the log once with an empty set. If a code is already in the set, return
true. Otherwise add it. At the end, returnfalse.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Keep a set of the codes already let in, so checking each new scan is one lookup instead of a search.
Trace [4021, 7788, 1290, 7788, 5003]:
- 4021: new. Set: {4021}.
- 7788: new. Set: {4021, 7788}.
- 1290: new. Set: {4021, 7788, 1290}.
- 7788: already in the set. Return
true; 5003 is never looked at.
Stopping early pays off: if the copy comes in near the start, you are done almost at once.
function hasRepeat(codes) {
const seen = new Set();
for (const code of codes) {
if (seen.has(code)) return true; // scanned before
seen.add(code);
}
return false;
}def has_repeat(codes):
seen = set()
for code in codes:
if code in seen: # scanned before
return True
seen.add(code)
return FalseRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.