Leetcode Problem 217: Contains Duplicate
Problem description:
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.
Python solution Link to heading
# leetcode_217.py
class Solution:
def containsDuplicate(self, nums) -> bool:
n = len(nums)
occurrences = {}
for i in range(0, n):
occurrences[nums[i]] = occurrences.get(nums[i], 0) + 1
if occurrences.get(nums[i]) > 1:
return True
return False
Javascript solution Link to heading
// leetcode_217.js
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
var n = nums.length;
var occurrences = {};
for (let i = 0; i < n; i++) {
occurrences[nums[i]] = (occurrences[nums[i]] ?? 0) + 1;
if (occurrences[nums[i]] > 1) {
return true
}
}
return false;
};
Python statistics Link to heading
Runtime: 596 ms - beats 43.40 % of python3 submissions
Memory Usage: 25.9 MB -- beats 93.86 % of python3 submissions
Javascript statistics Link to heading
Runtime: 112 ms -- beats 60.21 % of javascript submissions
Memory Usage: 51.4 MB -- beats 32.62 % of javascript submissions
Complexity analysis Link to heading
- Time: $ O(n) $
- Space: $ O(n) $ since size of map
occurrences
depends on size of distinct values in inputnums
Share on: