💡
Exercise 8

Contains Duplicate 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Our first LeetCode problem! 🎉 This is LeetCode #217: Contains Duplicate.

Given an integer array nums, return True if any value appears at least twice, and False if every element is distinct.

Approach 1: Brute Force — O(n²)
Compare every pair. Works but slow.

# Brute force — DON'T use this! def containsDuplicate(nums): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] == nums[j]: return True return False

Approach 2: Using a Set — O(n)
A set only stores unique values. If we try to add something that already exists, we found a duplicate!

💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀

Approach 3: One-liner
If the set is smaller than the list, there must be duplicates.

def containsDuplicate(nums): return len(set(nums)) != len(nums)

Complexity: Time O(n), Space O(n) — we store up to n elements in the set.

📋 Instructions
Implement the `containsDuplicate(nums)` function using the **set approach** (Approach 2). Don't use the one-liner — practice the logic! The function should: - Return `True` if any element appears more than once - Return `False` if all elements are unique Test cases are provided below.
Simplest: Use a set! If you see a number that's already in the set → duplicate found. Time O(n), Space O(n). Or sort first and check adjacent elements: O(n log n), O(1).
⚠️ Try solving it yourself first — you'll learn more!
# Optimal solution — O(n) time, O(n) space
def containsDuplicate(nums):
    seen = set()
    for num in nums:
        if num in seen:       # O(1) lookup!
            return True
        seen.add(num)
    return False
🧪 Test Cases
Input
containsDuplicate([1, 2, 3, 1])
Expected
True
Boolean check
Input
containsDuplicate([1, 2, 3, 4])
Expected
False
Boolean check
Input
containsDuplicate([1, 1, 1, 3, 3, 4])
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.