ThuyNT13/algorithm-practice

remove duplicates in-place from array - won't remove dupes for repeats greater than 3

Closed this issue · 2 comments

I think what might be happening here is that in your for loop, your index auto-increments regardless of whether or not you're splicing. Here, I do a similar thing, but I use a while loop instead, so that I can choose not to increment the index when I'm splicing:

const removeDuplicates = function(nums) {
    let i = 0;
    while(i < nums.length) {
        if(nums[i] == nums[i-1]) {
            nums.splice(i, 1);
            // don't increment the index here, since the array has shrunken in size, we'll want to check the same index on the next loop
        } else {
            i++;
        }
    }

    return nums.length;
}

// These all pass:
console.assert(removeDuplicates([1]) == 1);
console.assert(removeDuplicates([1,2]) == 2);
console.assert(removeDuplicates([]) == 0);
console.assert(removeDuplicates([1,2,2]) == 2);
console.assert(removeDuplicates([1,2,2,2]) == 2);
console.assert(removeDuplicates([2,2,2]) == 1);
console.assert(removeDuplicates([2,2,2,3]) == 2);
console.assert(removeDuplicates([2,2,3,3]) == 2);

@thinhngo I communicated with a friend and she gave me some insight into what the problem was actually asking for, it was very confusing. That and the lazy hack that occurred to me of just setting a counter that incremented every time the nums[i] and nums[i-1] were not the same - I would essentially get the length of the new collection of unique numbers.

The while loop does indeed offer the control needed for when to increment the indices and I needed 2 of them going. The org iterating through the "original" array, and the count incrementing as the index for the "new" array.

The latest solution passed the test that I rewrote having a better idea of what output to expect, but when I tried to pass it through Leet Code, adjusting again for the output, appeared to have a runtime issue as it got hung up on a super long array.

So one step closer but not passing.

https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/