Given a sequence of enqueue and dequeue operations, return a result of their execution without using a queue implementation from a library. Use two stacks to implement queue.
Operations are given in the form of a linked list, and you need to return the result as a linked list, too. Operations:
{
"operations": [1, -1, 2, -1, -1, 3, -1]
}
Output:
[1, 2, -1, 3]
Here is how we would execute the operations and build the result list:
Operation | Queue contents after the operation | Result list after the operation |
---|---|---|
1 | [1] | [] |
-1 | [] | [1] |
2 | [2] | [1] |
-1 | [] | [1, 2] |
-1 | [] | [1, 2, -1] |
3 | [3] | [1, 2, -1] |
-1 | [] | [1, 2, -1, 3] |
{
"operations": [0, 1, 2, -1, 3]
}
Output:
[0]
The only dequeue operation results in the first enqueued element, 0, to be appended to the result list.
Constraints:
operations
<= 2 * 109We have provided two solutions. We will refer to the length of given linked list operations
as N
.
Any time we process an operation that puts a number to the queue, we need to store it somewhere. We are only allowed to use stacks to store numbers, so let’s be pushing all enqueued numbers into stack1
.
Any time an operation tells us to retrieve a number from the queue, that number would be at the bottom of stack1
then. To access it we’d need to pop all the numbers from there. Luckily we are allowed to use another stack. So we can temporarily push all the numbers into stack2
and access the desired number from the bottom of stack1
. After that we can push all the remaining numbers back from stack2
to stack1
. They will end up being in the same order as they were there before the dequeue operation, and that works for us.
O(N2).
For processing all N
operations. Every dequeue operation requires moving around all the numbers so far enqueued, that makes the dequeue operation O(N).
O(N).
Because we never store more than N
numbers.
O(N).
Input, output and temporary data structures are all O(N). So, O(N) + O(N) + O(N) = O(N).
/*
Asymptotic complexity in terms of number of operations:
* Time: O(n^2).
* Auxiliary space: O(n).
* Total space: O(n).
*/
LinkedListNode* insert_node(
LinkedListNode *head, LinkedListNode *tail, int val)
{
if (head == NULL)
{
head = new LinkedListNode(val);
tail = head;
}
else
{
LinkedListNode *node = new LinkedListNode(val);
tail->next = node;
tail = tail->next;
}
return tail;
}
int dequeue(stack<int> &s1, stack<int> &s2)
{
if (s1.empty()) return -1;
// Pop all elements from first to second stack.
while (s1.empty() == false)
{
s2.push(s1.top());
s1.pop();
}
// Head of the second stack is the element to dequeue.
int val = s2.top();
s2.pop();
// Shovel all elements back to the first stack.
while (s2.empty() == false)
{
s1.push(s2.top());
s2.pop();
}
return val;
}
LinkedListNode* implement_queue(LinkedListNode* operations)
{
stack<int> s1, s2;
LinkedListNode *head = NULL;
LinkedListNode *tail = NULL;
while (operations != NULL)
{
if (operations->value >= 0)
{
s1.push(operations->value);
}
else
{
tail = insert_node(head, tail, dequeue(s1, s2));
if (head == NULL)
{
head = tail;
}
}
operations = operations->next;
}
return head;
}
Let’s imagine that we started with the brute force solution described above and came to this situation:
stack1 = [1, 2, 3]
, stack2 = []
, next operation: -1
To dequeue, we move all numbers from stack1
to stack2
:
stack1 = []
, stack2 = [3, 2]
, add append number 1 to the result
.
Now we can notice that stack2
has all the remaining numbers in the order that’s perfect for us. For example, if the next operation is -1, we can simply pop and return number 2 from stack2
- a constant time operation.
We can dequeue elements this way if we leave them in stack2
, but what about enqueueing new ones? It turns out that we can push them in stack1
, and they can remain there until stack2
is empty. Once stack2
is empty and another dequeue operation comes, we can do what was described two paragraphs ago: pop all numbers from stack1
and push them into stack2
.
O(N).
Enqueue operation takes constant time, clearly. Let us examine dequeue operation.
Most dequeue operations will just need to pop one number from stack2
, that’s constant time. Some dequeue operations however will need to move some numbers from stack1
to stack2
.
Amortized time complexity of the dequeue operation is constant and intuitively we can observe that we never move any given number more than once between stack1
and stack2
(that’s constant time per number).
Overall time complexity of the algorithm would be O(N) since we process N
operations, taking constant time per operation (amortized).
O(N).
As we never store more than N
numbers in our stacks.
O(N).
/*
Asymptotic complexity in terms of number of operations:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
LinkedListNode* insert_node(
LinkedListNode *head, LinkedListNode *tail, int val)
{
if (head == NULL)
{
head = new LinkedListNode(val);
tail = head;
}
else
{
LinkedListNode *node = new LinkedListNode(val);
tail->next = node;
tail = tail->next;
}
return tail;
}
int dequeue(stack<int> &s1, stack<int> &s2)
{
if (s1.empty() && s2.empty())
{
return -1;
}
// If second stack isn't empty, pop and return from it.
if (s2.empty() == false)
{
int val = s2.top();
s2.pop();
return val;
}
// Otherwise pop all elements from first to second stack.
while (s1.empty() == false)
{
s2.push(s1.top());
s1.pop();
}
// And then pop and return head of the second stack.
int val = s2.top();
s2.pop();
return val;
}
LinkedListNode* implement_queue(LinkedListNode* operations)
{
stack<int> s1, s2;
LinkedListNode *head = NULL;
LinkedListNode *tail = NULL;
while (operations != NULL)
{
if (operations->value >= 0)
{
s1.push(operations->value);
}
else
{
tail = insert_node(head, tail, dequeue(s1, s2));
if (head == NULL)
{
head = tail;
}
}
operations = operations->next;
}
return head;
}
We hope that these solutions to implement queue using two stacks problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart's FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Given a sequence of enqueue and dequeue operations, return a result of their execution without using a queue implementation from a library. Use two stacks to implement queue.
Operations are given in the form of a linked list, and you need to return the result as a linked list, too. Operations:
{
"operations": [1, -1, 2, -1, -1, 3, -1]
}
Output:
[1, 2, -1, 3]
Here is how we would execute the operations and build the result list:
Operation | Queue contents after the operation | Result list after the operation |
---|---|---|
1 | [1] | [] |
-1 | [] | [1] |
2 | [2] | [1] |
-1 | [] | [1, 2] |
-1 | [] | [1, 2, -1] |
3 | [3] | [1, 2, -1] |
-1 | [] | [1, 2, -1, 3] |
{
"operations": [0, 1, 2, -1, 3]
}
Output:
[0]
The only dequeue operation results in the first enqueued element, 0, to be appended to the result list.
Constraints:
operations
<= 2 * 109We have provided two solutions. We will refer to the length of given linked list operations
as N
.
Any time we process an operation that puts a number to the queue, we need to store it somewhere. We are only allowed to use stacks to store numbers, so let’s be pushing all enqueued numbers into stack1
.
Any time an operation tells us to retrieve a number from the queue, that number would be at the bottom of stack1
then. To access it we’d need to pop all the numbers from there. Luckily we are allowed to use another stack. So we can temporarily push all the numbers into stack2
and access the desired number from the bottom of stack1
. After that we can push all the remaining numbers back from stack2
to stack1
. They will end up being in the same order as they were there before the dequeue operation, and that works for us.
O(N2).
For processing all N
operations. Every dequeue operation requires moving around all the numbers so far enqueued, that makes the dequeue operation O(N).
O(N).
Because we never store more than N
numbers.
O(N).
Input, output and temporary data structures are all O(N). So, O(N) + O(N) + O(N) = O(N).
/*
Asymptotic complexity in terms of number of operations:
* Time: O(n^2).
* Auxiliary space: O(n).
* Total space: O(n).
*/
LinkedListNode* insert_node(
LinkedListNode *head, LinkedListNode *tail, int val)
{
if (head == NULL)
{
head = new LinkedListNode(val);
tail = head;
}
else
{
LinkedListNode *node = new LinkedListNode(val);
tail->next = node;
tail = tail->next;
}
return tail;
}
int dequeue(stack<int> &s1, stack<int> &s2)
{
if (s1.empty()) return -1;
// Pop all elements from first to second stack.
while (s1.empty() == false)
{
s2.push(s1.top());
s1.pop();
}
// Head of the second stack is the element to dequeue.
int val = s2.top();
s2.pop();
// Shovel all elements back to the first stack.
while (s2.empty() == false)
{
s1.push(s2.top());
s2.pop();
}
return val;
}
LinkedListNode* implement_queue(LinkedListNode* operations)
{
stack<int> s1, s2;
LinkedListNode *head = NULL;
LinkedListNode *tail = NULL;
while (operations != NULL)
{
if (operations->value >= 0)
{
s1.push(operations->value);
}
else
{
tail = insert_node(head, tail, dequeue(s1, s2));
if (head == NULL)
{
head = tail;
}
}
operations = operations->next;
}
return head;
}
Let’s imagine that we started with the brute force solution described above and came to this situation:
stack1 = [1, 2, 3]
, stack2 = []
, next operation: -1
To dequeue, we move all numbers from stack1
to stack2
:
stack1 = []
, stack2 = [3, 2]
, add append number 1 to the result
.
Now we can notice that stack2
has all the remaining numbers in the order that’s perfect for us. For example, if the next operation is -1, we can simply pop and return number 2 from stack2
- a constant time operation.
We can dequeue elements this way if we leave them in stack2
, but what about enqueueing new ones? It turns out that we can push them in stack1
, and they can remain there until stack2
is empty. Once stack2
is empty and another dequeue operation comes, we can do what was described two paragraphs ago: pop all numbers from stack1
and push them into stack2
.
O(N).
Enqueue operation takes constant time, clearly. Let us examine dequeue operation.
Most dequeue operations will just need to pop one number from stack2
, that’s constant time. Some dequeue operations however will need to move some numbers from stack1
to stack2
.
Amortized time complexity of the dequeue operation is constant and intuitively we can observe that we never move any given number more than once between stack1
and stack2
(that’s constant time per number).
Overall time complexity of the algorithm would be O(N) since we process N
operations, taking constant time per operation (amortized).
O(N).
As we never store more than N
numbers in our stacks.
O(N).
/*
Asymptotic complexity in terms of number of operations:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
LinkedListNode* insert_node(
LinkedListNode *head, LinkedListNode *tail, int val)
{
if (head == NULL)
{
head = new LinkedListNode(val);
tail = head;
}
else
{
LinkedListNode *node = new LinkedListNode(val);
tail->next = node;
tail = tail->next;
}
return tail;
}
int dequeue(stack<int> &s1, stack<int> &s2)
{
if (s1.empty() && s2.empty())
{
return -1;
}
// If second stack isn't empty, pop and return from it.
if (s2.empty() == false)
{
int val = s2.top();
s2.pop();
return val;
}
// Otherwise pop all elements from first to second stack.
while (s1.empty() == false)
{
s2.push(s1.top());
s1.pop();
}
// And then pop and return head of the second stack.
int val = s2.top();
s2.pop();
return val;
}
LinkedListNode* implement_queue(LinkedListNode* operations)
{
stack<int> s1, s2;
LinkedListNode *head = NULL;
LinkedListNode *tail = NULL;
while (operations != NULL)
{
if (operations->value >= 0)
{
s1.push(operations->value);
}
else
{
tail = insert_node(head, tail, dequeue(s1, s2));
if (head == NULL)
{
head = tail;
}
}
operations = operations->next;
}
return head;
}
We hope that these solutions to implement queue using two stacks problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart's FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Attend our free webinar to amp up your career and get the salary you deserve.