Home:ALL Converter>LeetCode Javascript - Remove Duplicates from a Sorted Array - Return Array issue

LeetCode Javascript - Remove Duplicates from a Sorted Array - Return Array issue

Ask Time:2022-01-01T14:03:35         Author:Avaneesh Ramaseshan

Json Formatter

LeetCode problem 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.

var removeDuplicates = function (nums) {
    // Iterating the full array
    for (let i = 0; i < nums.length; i++) {
        // Checking for the repeating number
        if (nums[i] === nums[i + 1]) {
            // Removing the element which is repeating
            nums = nums.slice(0, i + 1).concat(nums.slice(i + 2));
            // Resetting the index after removing the element
            i--;
        }
    }
    console.log(nums);
    return nums.length;
};

console.log(removeDuplicates([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4]));

This is the output of the above JS code on Visual Studio Code.

I am not able to submit this code to LeetCode. The expected output is the edited nums array, whereas my output doesn't match. How do I resolve this issue?

Author:Avaneesh Ramaseshan,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70547201/leetcode-javascript-remove-duplicates-from-a-sorted-array-return-array-issue
yy