Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

Implement Queue Using Two Stacks Problem

Implement Queue Using Two Stacks Problem Statement

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:

  • A non-negative integer means "enqueue me".
  • -1 means
    • If the queue is not empty, dequeue current head and append it to the result.
    • If the queue is empty, append -1 to the result.

Example One

{
"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]

Example Two

{
"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.

Notes

Constraints:

  • -1 <= value in the list of operations <= 2 * 109
  • 1 <= number of operations <= 105
  • There will be at least one dequeue (-1) operation

We have provided two solutions. We will refer to the length of given linked list operations as N.

Implement Queue Using Two Stacks Solution 1: Brute Force

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.

Time Complexity

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).

Auxiliary Space Used

O(N).

Because we never store more than N numbers.

Space Complexity

O(N).

Input, output and temporary data structures are all O(N). So, O(N) + O(N) + O(N) = O(N).

Code For Implement Queue Using Two Stacks Solution 1: Brute Force

/*
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;
}

Implement Queue Using Two Stacks Solution 2: Optimal

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.

Time Complexity

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).

Auxiliary Space Used

O(N).

As we never store more than N numbers in our stacks.

Space Complexity

O(N).

Code For Implement Queue Using Two Stacks Solution 2: Optimal

/*
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.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Implement Queue Using Two Stacks Problem

Implement Queue Using Two Stacks Problem Statement

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:

  • A non-negative integer means "enqueue me".
  • -1 means
    • If the queue is not empty, dequeue current head and append it to the result.
    • If the queue is empty, append -1 to the result.

Example One

{
"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]

Example Two

{
"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.

Notes

Constraints:

  • -1 <= value in the list of operations <= 2 * 109
  • 1 <= number of operations <= 105
  • There will be at least one dequeue (-1) operation

We have provided two solutions. We will refer to the length of given linked list operations as N.

Implement Queue Using Two Stacks Solution 1: Brute Force

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.

Time Complexity

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).

Auxiliary Space Used

O(N).

Because we never store more than N numbers.

Space Complexity

O(N).

Input, output and temporary data structures are all O(N). So, O(N) + O(N) + O(N) = O(N).

Code For Implement Queue Using Two Stacks Solution 1: Brute Force

/*
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;
}

Implement Queue Using Two Stacks Solution 2: Optimal

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.

Time Complexity

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).

Auxiliary Space Used

O(N).

As we never store more than N numbers in our stacks.

Space Complexity

O(N).

Code For Implement Queue Using Two Stacks Solution 2: Optimal

/*
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.

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar

Recommended Posts

All Posts