Can You Improve the Time Complexity of Building a Queue with Stacks?

  • Thread starter Thread starter Shackman
  • Start date Start date
  • Tags Tags
    Building Queue
AI Thread Summary
The discussion centers around implementing a queue using stacks, focusing on achieving the fastest possible performance. The proposed method involves using two stacks: items are pushed onto the first stack during enqueue operations. For dequeue operations, all items must be popped from the first stack and pushed onto the second stack, resulting in a time complexity of O(n^2) in the worst case. Suggestions for improvement include exploring alternative methods to reduce the time complexity and questioning the validity of using a queue of stack pointers, with one stack per object. The conversation emphasizes the need for a more efficient solution to manage the enqueue and dequeue operations effectively.
Shackman
Messages
22
Reaction score
2
Hello, I'm tasked with building a queue from as many stacks as I'd like, trying to get the fastest implementation possible. The best I can think of is using two stacks and as you enqueue items you push them on the first stack stack, but every time you want to dequeue if there are n items enqueue'd you have to pop each one individually and push them onto the second stack for n-1 times, then pop the first item enqueue'd and return it. Then any dequeue is easy..simply popping off the second stack because the order is reversed. If you want to enqueue again though, you'd have to do the reverse and pop each item off the second and push it back onto the first another n-1 times. So it looks like worst case it is O(n^2). Can anyone think of something better or help me improve this?
 
Technology news on Phys.org
Would it be cheating to use a queue of stack pointers and use one stack per object?
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top