Grind 75 Question 25: Contains Duplicate

This solution is twice as nice. See what I did there?

The Problem

The Initial Attempts

This problem is seriously so simple. It’s really a morale-booster, after all these linked lists and binary trees! My whiteboard code comes together in under five minutes and passes muster:

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    	nums.sort();
	for(i=0; i < nums.length -1; i++){
		if(nums[i] == nums[i+1]) return true;
	}
	return false;
};

But it’s not enough. I know there’s another way to solve this problem: hashmap time! Will it run faster? Use less memory? I plug it in and give it a whirl.

The (Second!) Solution

var containsDuplicate = function(nums) {
    
    let values = new Map();
    
	for(i=0; i < nums.length; i++){
		if(values.has(nums[i])){
            return true
        } else values.set(nums[i], i)
	}
	return false;
};

The answer to my question is: it uses the exact same amount of memory and runs about 1/3 faster.

A twist: I apparently solved this using a Set() back in June. Whaaat! I vaguely remember looking up what a set was, but I have no idea what prompted that. Clearly I didn’t retain that information. (Although, if I was looking up how to solve this problem back in June and can now do it two different ways with my eyes closed in under 5 minutes, maybe that’s a sign of how far I’ve come in just a month.)

What I Learned

  1. Mostly this: you’ve got an array that needs manipulated? I’m your gal.
  2. Sets are a thing, who knew?

Cool beans. The end of Week 2 means I’m officially all done with the easy stuff. Now onto medium questions, eep. Also — finishing question 25 means I’m 1/3 of the way through this! Not bad! At least, not yet…

1

min
read

Begin typing your search above and press return to search. Press Esc to cancel.