DevPath

← All problems

Contains Duplicate

Easy arrays · hashing

Description

Given an array of values, return true if any value appears at least twice, and false if every element is distinct.

Constraints

1 <= n <= 100000

Examples

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

Output: true

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

Output: false

Hints (1)
  • A set answers “have I seen this before?” in constant time.

Solutions

Track seen values in a map. · Time O(n) · Space O(n)

func containsDuplicate(nums []int) bool {
    seen := map[int]bool{}
    for _, n := range nums {
        if seen[n] {
            return true
        }
        seen[n] = true
    }
    return false
}

Create a free account to submit solutions, track progress and save problems.

Create account