0

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

var removeDuplicates = function(nums) {
    return nums.filter((num,i) => {
        return nums.splice(0, i).includes(nums[i]) ? false : true;
    }).length;
};
10
  • 5
    Your question should include: What is Leetcode and what error does it throw. Your code does not fit the requirements cause Array#filter creates a new array. Commented Sep 2, 2020 at 11:54
  • 4
    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. makes it quite clear that your code would not work because you are allocating O(n) extra memory (and not modifying the array in-place). Commented Sep 2, 2020 at 11:56
  • @trincot The OP is returning the length of the filtered array. Commented Sep 2, 2020 at 12:05
  • 1
    You need to look towards the common for cycle and splice for remove the duplicates in-place Commented Sep 2, 2020 at 12:08
  • 1
    @AbbasEbadian It allocates more than O(1) memory, so it doesn't qualify. Commented Sep 2, 2020 at 12:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.