Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    A queue made of two stacks

    EasyAbout 15 minFreeLearn it: Queues and Deques in C#: Queue<T>, Two-Stack Queues and Sliding Window Maximum

    The task

    A print service handles jobs in the order they arrive, but the library your team may use for it offers only Stack<int>.

    Complete the class TwoStackQueue, a first-in, first-out queue of ints that keeps its items only in Stack<int> fields. Enqueue(x) adds x at the back. Dequeue() removes and returns the item at the front. Peek() returns the front item without removing it. Count is the number of items. Dequeue and Peek throw InvalidOperationException when the queue is empty.

    Signature

    public sealed class TwoStackQueue
    public int Count { get; }
    public void Enqueue(int x)
    public int Dequeue()
    public int Peek()

    Examples

    • Enqueue(1), Enqueue(2), Enqueue(3), then Dequeue() three times → 1, 2, 3. First in, first out.
    • Enqueue(1), Enqueue(2), Dequeue(), Enqueue(3), Dequeue(), Dequeue() → 1, 2, 3. An item added later waits behind the older ones.

    Limits: Up to 450,000 operations in any order; together they must finish in time, so a Dequeue must not move every item every time.

    The tests check: the order, Enqueue and Dequeue mixed, that Peek does not remove, Count, both exceptions on an empty queue, using the queue again after it was emptied, and 450,000 operations in time.

    Hints

      The solution opens by itself when all tests pass. You remember more if you try first.

      Sign in to see the solution

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public sealed class TwoStackQueue
      {
          // Keep the items only in Stack<int> fields.
      
          public int Count => throw new NotImplementedException();
      
          public void Enqueue(int x)
          {
              throw new NotImplementedException();
          }
      
          public int Dequeue()
          {
              throw new NotImplementedException();
          }
      
          public int Peek()
          {
              throw new NotImplementedException();
          }
      }

      Sign in to run and submit your code. It stays here while you do.