0

I know I did something wrong, I'm just trying to figure out why my hashmap solution isn't giving me the right answer for this leetcode problem.

The problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

My solution:

var removeDuplicates = function(nums) {
    let map = new Map();

    for(var i = 0; i < nums.length; i++){
        if(nums[i] in map){
            nums.splice(i, 1)
        }
        else{
            map[nums[i]] = i;
        }
    }
};

UPDATE: This is NOT a duplicate. The new information that I learned is that using splice WILL update the index. That information is missing from the question referred to as the 'duplicate'

User9123
  • 675
  • 1
  • 8
  • 20
  • You can't use `in` with Map. Well, you *can*, but it doesn't do what you think it does. You need to use `map.has(nums[i])`. (Also for this you're probably better off with a Set.) Oh, and also, that's not how you put something in a Map; if you're going to do that just use a plain object, not a Map or a Set. (A plain object will work fine.) – Pointy Aug 30 '23 at 16:35
  • 1
    Also you're going to run into a problem with your loop, because splicing out an element of the array will mean that `i` will increment effectively twice instead of once. – Pointy Aug 30 '23 at 16:36
  • @Pointy thank you, it was because it was incrementing after the splice, post that as the answer and ill give you the top comment – User9123 Aug 30 '23 at 16:38
  • Also, to *add* things to a map, you need `map.set(key, value)` not `map[key] = value`. With that said, you don't even seem to need a map here. You're not using the key-value pairs, you're just using the fact that a key exists or not. A Set is the more appropriate data structure. – VLAZ Aug 30 '23 at 16:38
  • I guess the problem with your solution is that you're trying to modify an array while iterating over it, causing unexpected behaviour because the indices keep changing when you splice the array – esQmo_ Aug 30 '23 at 16:39
  • "*The new information that I learned is that using splice WILL update the index. That information is missing from the question referred to as the 'duplicate'*" How is it missing? [The top answer](https://stackoverflow.com/a/9882349) ***starts*** with the following: "The array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed" – VLAZ Aug 30 '23 at 16:46

0 Answers0