⚡ TL;DR
Solve Contains Duplicate in Go with working code. Hash Set (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Contains Duplicate (#217 — Easy): 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.
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.
Example:
Input: nums = [1,2,3,1]
Output: trueApproach: Hash Set (Optimal)
Time: O(n) | Space: O(n)
A hash set rejects duplicate insertions. In Python, comparing lengths of list vs set is the idiomatic one-liner.
func containsDuplicate(nums []int) bool {
seen := make(map[int]bool)
for _, num := range nums {
if seen[num] { return true }
seen[num] = true
}
return false
}
func main() {
fmt.Println(containsDuplicate([]int{1,2,3,1})) // true
fmt.Println(containsDuplicate([]int{1,2,3,4})) // false
}Key Takeaways
- Start with the brute-force approach to understand the problem
- Hash Set (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Contains Duplicate in Python
- Contains Duplicate in Dart
- Contains Duplicate in Swift
- Two Sum in Go
- Remove Duplicates from Sorted Array in Go
- Maximum Subarray in Go
FAQ
What is the best approach to solve Contains Duplicate in Go?
The recommended approach is Hash Set (Optimal), which runs in O(n) time with O(n) space. The full Go implementation is shown above.
What is the time complexity of Contains Duplicate in Go?
Using Hash Set (Optimal), the time complexity is O(n) and the space complexity is O(n).
Happy coding!
