Implement Stack using Deque
Pattern: Implementation
A deque allows adding and removing at both ends in O(1). Use only one end, the back, and it behaves as a stack: push adds at the back, pop and top use the back.
The problem
Build a stack class DequeStack with push, pop, top and isEmpty, using the library's deque (ArrayDeque,
std::deque, collections.deque). The linked page also builds a queue from a deque; a queue uses one end to add and the
other to remove.
On an empty structure, pop, top and peek return -1. This is this guide's own rule; the linked page does not say what happens.
Think first
- How many ends of the deque does a stack need?
- Which deque calls add and remove at the back?
- What would a queue use instead?
Hints
Brute force, and why it fails
No slower version is needed; this is about choosing the right end.
The key insight
Restricting a deque to one end turns it into a stack; to opposite ends, a queue.
Dry run
push(5), push(10): the deque is 5, 10 with the back on the right.
The plan
push(x): add x at the back
pop(): if empty: return -1; remove and return the back
top(): if empty: return -1; return the back
Complexity
- Time
O(1) per operation- Space
O(n)
Deque operations at either end are O(1).
Edge cases
- Empty deque:
-1. - Many pushes: the deque grows on its own.
I've built my logic, show the code
Java
import java.util.*;
class DequeStack {
private final Deque<Integer> dq = new ArrayDeque<>(); // only one end is used: the back is the top
public void push(int x) {
dq.addLast(x);
}
public int pop() {
return dq.isEmpty() ? -1 : dq.pollLast();
}
public int top() {
return dq.isEmpty() ? -1 : dq.peekLast();
}
public boolean isEmpty() {
return dq.isEmpty();
}
}C++
class DequeStack {
public:
deque<int> dq; // only one end is used: the back is the top
void push(int x) {
dq.push_back(x);
}
int pop() {
if (dq.empty()) return -1;
int x = dq.back();
dq.pop_back();
return x;
}
int top() {
return dq.empty() ? -1 : dq.back();
}
bool isEmpty() {
return dq.empty();
}
};Python
from collections import deque
class DequeStack:
def __init__(self):
self.dq = deque() # only one end is used: the back is the top
def push(self, x: int) -> None:
self.dq.append(x)
def pop(self) -> int:
return self.dq.pop() if self.dq else -1
def top(self) -> int:
return self.dq[-1] if self.dq else -1
def isEmpty(self) -> bool:
return not self.dqCommon mistakes
- Mixing ends (adding at the back and removing at the front), which builds a queue.
- Calling
popon an empty C++ deque, which is undefined behaviour.