Skip navigation
LeetCode 217, “Contains Duplicate”. NeetCode’s own solution page walks it Brute Force O(n^2) ->…
0:00

LeetCode 217, “Contains Duplicate”. NeetCode’s own solution page walks it Brute Force O(n^2) ->…

#techinterview #leetcode #hashtable

LeetCode 217, “Contains Duplicate”. NeetCode’s own solution page walks it Brute Force O(n^2) -> Sorting -> Hash Set O(n), and that is the whole trap: the answer everyone writes first is not wrong, it is quadratic. Given 50,000 numbers, does any value appear twice? seen = [] for x in nums: if x in seen: return True seen.append(x) This works. The trap is “x in seen”. It walks the list from the start, so one lookup costs as many comparisons as there are items in it: 50,000 items -> up to 50,000 checks for ONE lookup And the list grows with every number you store, so each lookup is more expensive than the last. Appending is cheap, it is the check that is not. Change one data structure: seen = set() for x in nums: if x in seen: return True seen.add(x) A set does not walk anything. It runs the value through a hash function, gets an address, and looks at that one slot: 50,000 items -> 1 check That is 50,000x fewer checks per lookup, worst case. Over the whole run (50,000 numbers, no duplicate) the list does 0 + 1 + 2 + ... + 49,999 = 1,249,975,000 comparisons. Measured on my machine, Python 3.12, exactly the code above: list 7.85 s, set 2.42 ms. The time gap is ~3,000x rather than 50,000x, because one hash costs more than one ==. It still wins by three orders of magnitude. What you trade: - a list keeps insertion order and index access, but has to scan to find - a set finds in one step, but costs extra memory and gives you no index - that one step is O(1) on average, not guaranteed: with enough collisions a hash lookup degrades to O(n) It is not either / or. The list holds your data. The set answers “have I seen this?”. Same idea outside Python: JS includes() vs Set.has(), Java List.contains() vs HashSet.contains(), PHP in_array() vs array_flip() + isset(). Save this for the next interview. #techinterview #leetcode #hashtable #codetips

Comments

Comments from the original post on Instagram

No comments yet