Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your solution is too complicated. To remove duplicates from an array, just do:

const removeDuplicates = (arr) => [...new Set(arr)]

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!