N8BIZ
N8BIZ

Reputation: 151

Remove duplicates from a sorted array - Leet Code 26

I'm working through a LeetCode challenge 26. Remove Duplicates from Sorted Array:

Given an integer array nums sorted 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 are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

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.

Upvotes: 0

Views: 2397

Answers (2)

trincot
trincot

Reputation: 350776

You shouldn't splice items from an array you are iterating, as such iteration is based on an incrementing index, and the deletion will cause array values to shift to the left. So this double effect will make you skip array values.

Moreover, you should avoid splicing all together as it represents an O(n) time complexity.

Also, the assignment says "Do not allocate extra space ... You must do this ... with O(1) extra memory.", so collecting values in a Map is not what you should do. As the input array is sorted, you don't need this map either.

Instead use two indices: one that will be used for reading a value, and one where a value will be written. The first one will run ahead of the latter when there are duplicates.

var removeDuplicates = function(nums) {
    if (nums.length === 0) return 0;
    let k = 0;
    for (let value of nums) {
        if (value !== nums[k]) {
            nums[++k] = value; 
        }
    }
    return k + 1;
};

Note that it is not necessary to modify the length of the array, as the code challenge says:

...the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Upvotes: 3

Nikita Skrebets
Nikita Skrebets

Reputation: 1542

Removing the element with index i using splice, the array elements shift. The next iteration starts, you look at the element on index i + 1. But as the elements shifted, you miss the element that was on position i + 1 and became the element on position i after the shift.

I assume that it would be wrong for me to post a correct answer as it is a challenge, other participants should solve it by themselves and not copy-paste an answer from here. So I'm just showing what do we get using current solution:

const 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;
};

const nums = [0,0,1,1,1,2,2,3,3,4]; // Input array
const expectedNums = [0,1,2,3,4]; // The expected answer with correct length

const k = removeDuplicates(nums); // Calls your implementation

console.log(nums.join(','))
console.log(expectedNums.join(','))

Upvotes: 0

Related Questions