I'm working through a LeetCode challenge 26. Remove Duplicates from Sorted Array:
Given an integer array
numssorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array
nums. More formally, if there arekelements after removing the duplicates, then the firstkelements ofnumsshould hold the final result. It does not matter what you leave beyond the firstkelements.Return
kafter placing the final result in the firstkslots ofnums.Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
I'm not sure why my answer isn't being accepted. I believe I'm misinterpreting something simple.
The issue:
My solution only returns an empty array even though I appear to have the correct answer for the baseline test. Is there something that I'm overlooking on the implementation in regard to the rules of the challenge? splice edits elements in place.... so I thought that would be fine.
Any suggestions would be appreciated.
var removeDuplicates = function(nums) {
const map = new Map();
let count = 0;
nums.forEach((item, i) => {
if (map.get(item) === undefined){
map.set(item, i);
} else if (map.get(item) !== undefined) {
nums.splice(i, 1);
nums.push('_');
count ++;
}
});
return count;
};
I have also posted this as a question on LeetCode's discussion section.
Mapprobably contradicts the challenge's instruction not to allocate another array.