How Switching from List to Set Cuts Duplicate-Check Complexity in Python
A developer working on a classic LeetCode problem — detecting duplicates in an integer array — initially used a Python list for lookups, assuming it would run in O(n) time. The approach was actually O(n²) because checking membership in a list requires scanning each element sequentially. Replacing the list with a set brought the solution to true O(n) time, since sets use hash-based lookups. The developer further simplified the logic to a single line: comparing the length of the original array against its set equivalent. The exercise highlights how a seemingly minor data structure choice can carry significant hidden performance costs.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in