Leetcod 217: Contains Duplicate

September 29, 2024 1 min read
Slide 1

neetcode/arrays-hashing/contains_duplicate.go

Notes

Problem

LeetCode 217 - Contains Duplicate

Solution

Use a hash map to keep track of seen numbers. Iterate through the array once, checking if each number is already in the map. If it is, return true (duplicate found). If not, add the number to the map. If we finish iterating without finding a duplicate, return false.

Analysis

Time Complexity: O(n) Space Complexity: O(n)

Code

package arrayshashing

func ContainsDuplicate(nums []int) bool {
	result := make(map[int]bool)
	for _, v := range nums {
		if _, exists := result[v]; exists {
			return true
		}
		result[v] = true
	}
	return false
}

Get in Touch

I'm always open to new opportunities and collaborations.

GitHub LinkedIn Twitter