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

239
Vistas
How to write a pop function for a stack in Javascript/Typescript in O(1)

I am trying to build my own stack in TypeScript and I am having trouble implementing a pop() function that can run in O(1) time complexity to mimic Javascript's native pop() function. I am able to delete the top-most item, but Javascript keeps the index in the stack as undefined. To combat this, I filter the stack to remove undefined, causing O(n) time complexity. Any other ideas to implement this in O(1) is appreciated. Current code:

public pop(): T {
        if (this.isEmpty()) {
            throw new Error('Empty Stack');
        }
        const popped = this.storage[this.size() - 1];
        this.stackSize--;
        delete (this.storage[this.size() - 1]);
        this.storage = this.storage.filter(x => x !== undefined);
        return popped;
    }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You don't need to actually remove the item from the array

if you simply call

this.stackSize--;

you implicitly say that you removed it

the thing is that you need to change all of your other functions to work with index instead of native functions

so the top() should be like

top(){

return this.stack[this.stackSize-1]
}


and so on...

This will achieve O(1)

about 4 years ago · Juan Pablo Isaza Denunciar

0

In JavaScript, you can shorten the array like this:

this.storage.length = this.storage.length-1
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