Question
You're given a list of numbers. You need to check whether any value appears more than once.
Return true
if any number is repeated. Otherwise, return false
.
Example
Input: [1, 2, 3, 4]
Output: false
Explanation: All numbers are unique.
Input: [3, 1, 2, 3]
Output: true
Explanation: The number 3 appears twice.
Input: [7]
Output: false
Explanation: Only one element.
My Notes
- We can use a hash map to track what we've seen.
- Loop through the list and add items to the map.
- If a number already exists in the map, return
true
. - This uses O(n) time and O(n) space.
- Map value can be
struct{}
since we don’t care about the value — just presence.
Why use struct{}
and not bool
?
- Zero allocation:
struct{}
uses 0 bytes — more memory-efficient thanbool
. - Clarity: Makes it explicit we're only tracking presence.
- Idiomatic Go: Common pattern for building "sets" using maps.
- Safer: No risk of logic mistakes from stored
true
/false
values.
package main import ( "fmt" ) func main() { result := containsDuplicate([]int{1,2,3,4,4,5,6,7}) fmt.Println(result) } func containsDuplicate(nums []int) bool { lookup := make(map[int]struct{}) for _, item := range nums { if _, ok := lookup[item]; ok { return true } lookup[item] = struct{}{} } return false }