Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

In JavaScript, you can shorten the array like this:

this.storage.length = this.storage.length-1
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda