Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Remove duplicates from a sorted array - Leet Code 26

I'm working through a LeetCode challenge 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.

I'm not sure why my answer isn't being accepted. I believe I'm misinterpreting something simple.

The issue:

My solution only returns an empty array even though I appear to have the correct answer for the baseline test. Is there something that I'm overlooking on the implementation in regard to the rules of the challenge? splice edits elements in place.... so I thought that would be fine.

Any suggestions would be appreciated.

var removeDuplicates = function(nums) {
    const map = new Map();
    let count = 0;
    nums.forEach((item, i) => {
        if (map.get(item) === undefined){
            map.set(item, i);
        } else if (map.get(item) !== undefined) {
            nums.splice(i, 1);
            nums.push('_');
            count ++;
        }
    });
    return count;
};

I have also posted this as a question on LeetCode's discussion section.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You shouldn't splice out items from an array that you are iterating, as such iteration is based on an incrementing index, and the deletion will cause array values to shift to the left. So this double effect will make that you skip array values.

Moreover, you should avoid splicing all together as it represents a O(n) time complexity.

Also, the assignment says "Do not allocate extra space ... You must do this ... with O(1) extra memory.", so collecting values in a Map is not what you are supposed to do. As the input array is sorted you really don't need this map either.

Instead use two indices: one that will be used for reading a value, and one where a value will be written. The first one will run ahead of the latter when there are duplicates.

var removeDuplicates = function(nums) {
    if (nums.length == 0) return 0;
    let k = 0;
    for (let value of nums) {
        if (value != nums[k]) {
            nums[++k] = value; 
        }
    }
    return k + 1;
};

Note that it is not necessary to modify the length of the array, as the code challenge says:

...the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Removing the element with index i using splice, the array elements shift. The next iteration starts, you look at the element on index i + 1. But as the elements shifted, you miss the element that was on position i + 1 and became the element on position i after the shift.

I assume that it would be wrong for me to post a correct answer as it is a challenge, other participants should solve it by themselves and not copy-paste an answer from here. So I'm just showing what do we get using current solution:

const removeDuplicates = function(nums) {
    const map = new Map();
    let count = 0;
    nums.forEach((item, i) => {
        if (map.get(item) === undefined){
            map.set(item, i);
        } else if (map.get(item) !== undefined) {
            nums.splice(i, 1);
            nums.push('_');
            count++;
        }
    });
    return count;
};

const nums = [0,0,1,1,1,2,2,3,3,4]; // Input array
const expectedNums = [0,1,2,3,4]; // The expected answer with correct length

const k = removeDuplicates(nums); // Calls your implementation

console.log(nums.join(','))
console.log(expectedNums.join(','))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda