217. Contains Duplicate
Asked at 19Bloomberg61Amazon58Microsoft57Google55Meta51Apple30Yahoo97Netflix69Capgemini68Airbnb66tcs65ZScaler63SAP62Accenture54IBM44Zoho42Nvidia39Infosys39Visa39
Problem
Return true if some value appears at least twice in the integer array nums, and false if all elements are distinct.
Example: [1,2,3,1] → true; [1,2,3,4] → false
Constraints: n ≤ 10⁵.
Insert into a set; if an element is already there, it's a duplicate.
Complexity: O(n) time, O(n) space (sorting gives O(n log n) / O(1)).
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
assert Solution().containsDuplicate([1, 2, 3, 1]) is True
assert Solution().containsDuplicate([1, 2, 3, 4]) is False
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) if (!seen.add(x)) return true; // add() returns false if present
return false;
}
}
func containsDuplicate(nums []int) bool {
seen := map[int]bool{}
for _, x := range nums {
if seen[x] {
return true
}
seen[x] = true
}
return false
}