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

243
Views
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 answers
Answer question

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 Report

0

In JavaScript, you can shorten the array like this:

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