Problem category:: Array, Hash table Neetcode Category:: Arrays and Hashing

https://leetcode.com/problems/contains-duplicate/

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.

Optimal

Dictionary (hash table)

Use a hash table based data structure, such as Dictionary, as we can check in average time whether an entry already exists (we do this up to n times over the entries)

  • time (average), space

Others

For every item, check every item ahead if it’s equal to it (2x nested for loops)

  • time, space
    • Will time out

Sorting

Use a sort (in place) first, then linear scan - check if prior element is identical

  • time, space
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        list.sort(nums)
        i = 1
        while i < len(nums):
            if nums[i-1] == nums[i]:
                return True
            i += 1
        return False