#217EasyHash Set

Contains Duplicate

Detect if any value appears at least twice using a hash set.

AmazonGoogleBloombergYahoo

Problem Statement

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Examples

Example 1

Input:nums = [1,2,3,1]
Output:true

Explanation: 1 appears at index 0 and 3.

Example 2

Input:nums = [1,2,3,4]
Output:false

Explanation: All elements are distinct.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Solutions

1
Brute Force — Nested Loops
TimeO(n²)SpaceO(1)

Compare every pair of elements. If any two are equal, return true. O(n²) time — fine for small inputs but too slow for n=10⁵.

Visual Animation
def containsDuplicate(nums: list[int]) -> bool:
    n = len(nums)
    for i in range(n):
        for j in range(i + 1, n):
            if nums[i] == nums[j]:
                return True
    return False

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Hash Set to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems