Contains Duplicate
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Tell whether any value appears at least twice in the list.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What is the cheapest thing to remember about each number you pass?
- Hint 2You only need yes or no, no counts or positions.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Exam hall: students walk in and sign the attendance sheet with their roll number. Before signing, the invigilator glances at the sheet. If that roll number is already there, someone signed twice (a proxy!). He does not compare with every student, he just checks the sheet.
- The obvious way
Compare every pair of numbers: O(n²). Or sort first and compare neighbours: O(n log n).
- The key insight
Keep an attendance sheet (a set). For each number: already on the sheet means a duplicate; otherwise add it. Looking something up in a set is one step, so the whole job is one walk through the list.
- The algorithm
- Start with an empty sheet (a set).
- For each number: is it already on the sheet? Then answer True.
- Otherwise write it on the sheet.
- Reached the end with no repeat? Answer False.
Watch it run
Examplenumbers = [1, 2, 3, 1]
Take 1. Not on the sheet, so sign it.
sheet: {1}Where people slip
- Sorting needs no extra memory but costs O(n log n); mention this trade-off in an interview.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def contains_duplicate(nums):
sheet = set() # numbers already signed
for number in nums:
if number in sheet:
return True # someone signed twice
sheet.add(number)
return False
# one-liner idea: len(set(nums)) != len(nums)Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.