Implement a stack and a queue, and state the time complexity of their operations.
ReportedSource: GeeksforGeeks interview experience: Accenture Associate Software Engineer
Stack: array/list with push/pop at the end, O(1). Queue: circular buffer or linked list for O(1) enqueue/dequeue (not list.pop(0)). In practice deque/ArrayDeque.
Constraints
- Input: first line q (number of commands). Then q lines, each one command: push x, pop, peek, enqueue x, dequeue, front, stack_size, queue_size.
- Output: one line for every command except push and enqueue. pop, peek, dequeue and front print the value, or EMPTY when the structure is empty. The size commands print an integer.
- 1 <= q <= 100000, -10^9 <= x <= 10^9.
- The stack and the queue are two separate structures that share one command stream.
Sample I/O
in: 5 push 1 push 2 peek pop pop
out: 2 2 1
in: 6 enqueue 1 enqueue 2 front dequeue dequeue queue_size
out: 1 1 2 0
in: 8 push 5 enqueue 7 push 6 pop dequeue stack_size queue_size peek
out: 6 7 1 0 5
Sign up to run your code in the sandbox.
Sign up to run code and get an AI review
You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.
Sign up freeHints
Reference solution
Stack (LIFO). push, pop, peek, all O(1).
class Stack:
def __init__(self): self.items = []
def push(self, x): self.items.append(x)
def pop(self):
if not self.items: raise IndexError('pop from empty stack')
return self.items.pop()
def peek(self): return self.items[-1] if self.items else None
Queue (FIFO). enqueue, dequeue, O(1). Avoid list.pop(0) (O(n)); use a circular buffer or linked list.
class Queue:
def __init__(self, cap):
self.buf, self.head, self.size = [None] * cap, 0, 0
def enqueue(self, x):
if self.size == len(self.buf): raise OverflowError('queue full')
self.buf[(self.head + self.size) % len(self.buf)] = x
self.size += 1
def dequeue(self):
if self.size == 0: raise IndexError('queue empty')
x = self.buf[self.head]
self.head = (self.head + 1) % len(self.buf); self.size -= 1
return x
In practice. Python collections.deque, Java ArrayDeque for both.
Classic follow-ups. Queue using two stacks (amortised O(1)), stack using queues, min-stack with O(1) getMin, applications (undo, bracket matching, BFS).