217. Contains Duplicate

The Guard

The Guard

You are a guard who has to sit through a list that contains all the booked seat numbers and ensure none of the seats are booked more than once. In Simple terms, you are given an array and you have to return true if all elements are unique, if one or more elements repeat in the array, you return false.

The Bruteforce

If you have ample time, you can just pick the first one, and compare it with the others, then pick the seconds and compare till you have compared the entire array, or have found an element that repeats.

The two algorithms

C++

Here, we will simply make a HashMap, or Unordered Map as in CPP. We iterate through the list and whenever we come across an element, we check if that exists in our map. If not, we add it. If it already does, it means duplicates exist and we quit the code. If we reach the end of the list, it means no duplicates were there

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) 
    {
         std::unordered_map<int, bool> myMap;
         for(int i=0;i<nums.size();i++)
         {
             if (myMap.count(nums[i]))
             {
                 return true;
             }
             else
             {
                 myMap[nums[i]] = true;
             }
         }
         return false;
    }
};

Rust

This is the first time I used HashSets. These are basically like hashmaps, but, instead of storing a key-value pair, they can simply store values. Then they can check if the value exists or not. Another cool thing I learnt is that you can set the capacity of a hashset to minimise data consumption.

use std::collections::HashSet;
impl Solution {
    pub fn contains_duplicate(nums: Vec<i32>) -> bool 
    {
        let mut index: HashSet<i32> = HashSet::with_capacity(nums.len());
        for i in 0..nums.len() 
        {
            if index.contains(&nums[i]) {
        return true;
    }
        index.insert(nums[i]);
        }
        return false;
    }
}

JavaScript

This was an interesting one. A datatype called sets exists in JavaScript. Using this, we can convert any list to a set in js. If you were attentive back in 6th class, you know that a set cannot have duplicate elements. So, if the size of our list and its set is different, there must have been some duplicates in this array.

This is the first time I just used sets in a actual question...

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) 
{
        let newSet = new Set(nums); 
        return newSet.size != nums.length;
};