LeetCode 217 Contains Duplicate Solution in Python

LeetCode Problem 217: Contains Duplicate (Python) I’m following the beginner LeetCode roadmap, and today I learned and completed problem #217 — Contains Duplicate. I used a set to achieve O(n) time complexity, with O(1) average-time lookups. The idea is simple: iterate through the list and add each number to a set. If you ever see a number that’s already in the set, you’ve found a duplicate, so you can stop immediately and return True. For example, if the list is [1, 3, 5, 3, 1], the set will grow to {1, 3, 5}. When you reach the 4th element (3), it’s already in the set, so the algorithm stops and returns True. Some of you might think it should keep going because there are two duplicates. That’s true, but for this problem you only need to know whether any duplicate exists, so stopping at the first one is enough.

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories