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;
};
kai
  • 6,702
  • 22
  • 38
  • 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. – kai Sep 02 '20 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). – briosheje Sep 02 '20 at 11:56
  • @trincot The OP is returning the length of the filtered array. – Aadit M Shah Sep 02 '20 at 12:05
  • I dont know if we just use `nums = new Set(nums).length` does it allocate new memory or not.Please let me know If somebody is aware how does it work.@kai @briosheje @trincot – AbbasEbadian Sep 02 '20 at 12:06
  • @AbbasEbadian That doesn't modify the input array. Also, I'm quite certain that that's not what the question is testing you on. – Aadit M Shah Sep 02 '20 at 12:08
  • 1
    You need to look towards the common `for` cycle and `splice` for _remove the duplicates in-place_ – Nikita Madeev Sep 02 '20 at 12:08
  • Leetcode has no way to see the content you generated. The new array you created is not accessible. Instead you are asked to mutate the existing array, which Leetcode can scan after running your code. – trincot Sep 02 '20 at 12:08
  • @AaditMShah Thanks.just wanted to know if `nums=new Set(nums)` allocates new memory or uses same, because the result wont be bigger than the first one. @trincot @kai – AbbasEbadian Sep 02 '20 at 12:11
  • 1
    @AbbasEbadian It allocates more than O(1) memory, so it doesn't qualify. – Aadit M Shah Sep 02 '20 at 12:12
  • You also need to `sort()` the array and have a pointer to shift back the next unique element as the problem statement says _It doesn't matter what you leave beyond the returned length._ – nice_dev Sep 02 '20 at 12:47

0 Answers0