Queues

- Fundamentals -

Linked Lsit Queue

1. Design a queue using a linked list.

The implementation should support the following operations in O(1) time:

  • enqueue(x): Add element x to the rear of the queue.
  • dequeue(): Remove and return the front element of the queue.
  • peek(): Return the front element without removing it.
  • isEmpty(): Return true if the queue is empty, otherwise false.
Parameter \ Case Best Case Worst CaseEdge Case
Input Parameters enqueue(1), dequeue() Series of operations (enqueue and dequeue) Calling dequeue() or peek() on empty queue
Output Expected front element Consistent FIFO output null for dequeue() or peek()
Explanation Constant-time insert/remove with minimal operations Queue handles high volume efficiently (O(1) still) Queue remains robust even when empty

Reverse Queue

2. Given a queue. Design an algorithm that returns the queue with elements in reverse order.

Parameter \ Case Best Case Worst CaseEdge Case
Input Parameters [1, 2] [1, 2, ..., 100000] [], [42]
Output [2, 1] [100000, ..., 2, 1] [], [42]
Explanation Small queue, minimal operations needed Very large queue; deep recursion/stack use Empty queue returns same; one-element unchanged

Circular Queue

3. Design and implement a Circular Queue data structure that uses a fixed-size array as underlying storage. The queue must behave in a circular manner — when the end of the array is reached, it wraps around to reuse empty slots at the beginning.

    The data structure should support the following operations in constant time (O(1)):

  • enqueue(value) – Add an element to the rear of the queue.
  • dequeue() – Remove the front element from the queue.
  • front() – Retrieve the front element (without removing it).
  • rear() – Retrieve the rear element (without removing it).
  • isEmpty() – Return true if the queue is empty; otherwise, false.
  • isFull() – Return true if the queue is full; otherwise, false.
Parameter \ Case Best Case Worst CaseEdge Case
Input Parameters Simple enqueue, dequeue with room in buffer Continuous enqueue-dequeue with wrap-around across buffer boundaries Only one space left, or adding/removing in an already full/empty buffer
Output Expected queue state and front/rear values Correctly wrapped indices and full/empty status Handles queue reset after full use, maintains correct front/rear/empty/full
Explanation Straightforward insert and remove Tests logic of circular movement, modulo arithmetic, full/empty boundary Tests queue behavior at minimum buffer size (e.g., size = 1) and max capacity

Two-Stack Queue Design

4. Design an algorithm that will implement first-in-first-out (FIFO) queue using two stacks.

The data structure should support the following operations:

  • enqueue(x) - Add element x to the back of the queue.
  • dequeue() - Removes the element from the front of the queue and returns it.
  • peek() - Get the front element.
  • isEmpty() - Return whether the queue is Empty.
Parameter \ Case Best case Worst caseEdge case
input enqueue(1), dequeue(), isEmpty() enqueue(1...n), dequeue(), peek() after full transfer enqueue(), dequeue(), then check isEmpty() on empty queue
outputCorrect element dequeued and false from isEmpty() All operations behave as expected even after full transfer true for isEmpty, appropriate error/exception on dequeue()
explanationNo need to transfer between stacks dequeue() must transfer all items from stack1 to stack2 Verifies correct handling when queue becomes empty again

- Intermediate Problems -

BFS using Queue

1. Given an unweighted graph represented as an adjacency list, and two nodes start and end.

Design an algorithm using Breadth- First Search (BFS) and a queue to return the shortest path (in terms of number of edges) from start to end. Id no path exists, return null.

The algorithm should return the path as an array of nodes from start to end, inclusive.

Parameter \ Case Best case Worst caseEdge case
input start and end are directly connected start and end are at maximum distance or deeply nested start === end or start/end disconnected
output[start, end] Longest valid shortest path (e.g., [A, B, ..., Z]) [start] or null
explanationBFS finds end in first layer BFS explores many levels before finding end No traversal needed (same node), or all nodes explored with no valid path

Level Order of Tree

2. Given the root of a binary tree. Design an algorithm that performs a level order traversal using a queue and return a list of node values level by level from top to bottom from left to right.

Binary Tree Node:


 class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

1234567[1],[2, 3],[4, 5, 6][]
Parameter \ Case Best case Worst caseEdge case
input Perfect binary tree (balanced) Skewed tree (like a linked list — only left/right) Empty tree or single node
outputEach level is fully populated and wide Each level has only one node [] for empty tree, or [[val]] for one node
explanationQueue processes levels efficiently Queue processes one node at a time Minimal or no processing needed

Sliding Window Maximum

3. Given an array of integers nums and an integer k, design an efficient algorithm that returns an array of the maximum values in every sliding window of size k, as the window moves from left to right across nums.

Each window must contain exactly k elements. The output should have (n - k + 1) elements, where n is the length of nums.

nums = [5, 5, 5, 5, 5], k=3Output = [5, 5, 5]Best CaseWorst Casenums = [1, 2, 3, 4, 5], k = 2Output [2, 3, 4, 5]nums = [2, 1, 3], k = 1output = [2, 1, 3]Edge Case:Input: nums = [3, 1, 4, 2], k = 4Output: [4]Input: nums = [1, 2], k = 3Output: []
Parameter \ Case Best case Worst caseEdge case
input All elements are equal Strictly increasing or decreasing array Length < k or k = 1 or k = n
outputSame repeated value Each window has different max Empty or same array as input
explanationEvery window gives same max value Max shifts every window → most updates Either 1-to-1 windows or no valid window

LIFO from FIFO

4. Design an algorithm that implements a Stack (LIFO) using one ot two queues (FIFO).

The algorithm should support the standard stack operations:

  • push(x): Push element x onto the stack.
  • pop(): Removes the element on the top of the stack.
  • top(): Get the top element.
  • isEmpty() Return wheter the stack is empty.
Parameter \ Case Best case Worst caseEdge case
input push(1), top(), pop() push(1...10000), pop() pop() or top() on empty stack
output1, 1 10000 Error / null / exception
explanationMinimal operations; each takes O(1) Large data causes O(n) operation in queue simulation Must handle empty-state gracefully

Binary Numbers from 1 to N

5. Given an integer 'N'. Design an algorithm that generates binary representations of all numbers from 1 to N in order, in numerical order.

Return the result as an array of binary strings.

Parameter \ Case Best case Worst caseEdge case
input N = 1 N = 100000 pop() or top() on empty stack
output["1"] ["1", "10", ..., binary(100000)] Error / null / exception
ExplanationOnly one binary number to compute Largest number of binary strings to generate; algorithm must be optimal Must return an empty array or handle 0 as invalid

1st Non-Repeating Character

6. Given a continuous stream of lowercase English characters, design an algorithm that returns a string where the i-th character represents the first non-repeating character in the stream up to index i. If no non-repeating character exists at a given point, return "#" for that position.

Parameter \ Case Best case Worst caseEdge case
input "abcd" "aabbcc" "" (empty stream)
output"aaaa" "######" ""
ExplanationAll characters are unique; each first non-repeating is the first char All characters repeat quickly; none remain non-repeating No characters to process

Rotten Oranges

7. Given a 2D Array Grid where each cell can have one of three values:

  • 0: Empty Cell
  • 1: Fresh Cell
  • 2: Rotten Cell

Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.

Design an algorithm that compute the minimum number of minutes that must elapse until no cell has a fresh orange. If it is impossible to rot all oranges, return -1.

Parameter \ Case Best case Worst caseEdge case
input [[2,1,1],[1,1,1],[0,1,1]] [[2,1,1],[1,1,0],[0,1,1]] [[0]], [[1]], [[2]]
output4 -1 0, -1, 0
ExplanationAll fresh oranges rot in 4 minutes from the initial rotten orange. Some fresh oranges are unreachable (isolated by 0s), so return -1. No characters to process
Edge cases: Only empty cell (0), only fresh (1) but no rotten, or already all rotten (2).