💻 Programming

Queue

Queue

A FIFO (First-In-First-Out) data structure. Data that enters first leaves first. Used in task scheduling, BFS, message queues, and more.

📖 Detailed Explanation

A queue is a linear data structure that follows the FIFO (First-In-First-Out) principle. It works on the same principle as a line at a bank counter: the person who lines up first is served first. Data is inserted (enqueue) at the rear and removed (dequeue) from the front. This is in contrast to the stack, which has a LIFO (Last-In-First-Out) structure.

Queues are divided into several types according to their purpose and implementation method. A linear queue is the basic FIFO structure, while a circular queue connects the end and the beginning of an array to use memory efficiently. A priority queue assigns a priority to each element so that elements with higher priority are processed first. A deque (double-ended queue) is an extended form that allows both insertion and deletion at either end.

The core operations of a queue have O(1) time complexity. The enqueue (insertion) and dequeue (deletion) operations only need to adjust pointers, so they run in constant time. The peek/front operation is also O(1) because it only returns the first element. isEmpty (checking whether the queue is empty) is also O(1), and in an array-based implementation, if the size is stored, the size operation is also O(1). However, searching for a specific element in a queue requires O(n) time.

In practice, queues are used as a core component in a variety of fields. Message queues (RabbitMQ, Kafka, etc.) are used for asynchronous communication between microservices. The BFS (breadth-first search) algorithm traverses a graph based on a queue. The queue structure is essential in operating system process/task scheduling, printer job management, web server request handling, and cache implementation (FIFO replacement policy).

📊 Types of Queues

Linear Queue

Basic FIFO structure. Implemented with an array or a linked list. Space may be wasted in an array implementation.

Circular Queue

Connects the end and the beginning of an array. Memory reuse improves space efficiency. Suitable for fixed-size buffers.

Priority Queue

Processes elements with higher priority first. Implemented with a heap. Used in Dijkstra's algorithm and task scheduling.

Deque

Insertion/deletion possible at both ends. Supports the characteristics of both stacks and queues. Used in sliding window problems.

⏱️ Time complexity

Operation Time complexity Description
enqueue (insertion) O(1) Add an element at the rear
dequeue (deletion) O(1) Remove an element from the front
peek / front O(1) Check the first element (without removing it)
isEmpty O(1) Check whether it is empty
size O(1) Return the number of elements
Search O(n) Find a specific element (sequential search)

💻 Code Example

# Python 큐 구현 예제
from collections import deque
from typing import Any, Optional


class Queue:
    """배열 기반 큐 구현"""
    def __init__(self):
        self._items = deque()  # deque는 양쪽 O(1) 연산 지원

    def enqueue(self, item: Any) -> None:
        """큐의 rear에 요소 추가 - O(1)"""
        self._items.append(item)

    def dequeue(self) -> Any:
        """큐의 front에서 요소 제거 및 반환 - O(1)"""
        if self.is_empty():
            raise IndexError("빈 큐에서 dequeue 시도")
        return self._items.popleft()

    def peek(self) -> Any:
        """front 요소 확인 (제거 없음) - O(1)"""
        if self.is_empty():
            raise IndexError("빈 큐에서 peek 시도")
        return self._items[0]

    def is_empty(self) -> bool:
        """큐가 비어있는지 확인 - O(1)"""
        return len(self._items) == 0

    def size(self) -> int:
        """큐의 크기 반환 - O(1)"""
        return len(self._items)

    def __len__(self) -> int:
        return self.size()

    def __repr__(self) -> str:
        return f"Queue({list(self._items)})"


class CircularQueue:
    """고정 크기 원형 큐 구현"""
    def __init__(self, capacity: int):
        self._capacity = capacity
        self._items = [None] * capacity
        self._front = 0
        self._rear = -1
        self._size = 0

    def enqueue(self, item: Any) -> bool:
        """원형 큐에 요소 추가 - O(1)"""
        if self.is_full():
            return False  # 또는 예외 발생
        self._rear = (self._rear + 1) % self._capacity
        self._items[self._rear] = item
        self._size += 1
        return True

    def dequeue(self) -> Optional[Any]:
        """원형 큐에서 요소 제거 - O(1)"""
        if self.is_empty():
            return None
        item = self._items[self._front]
        self._items[self._front] = None
        self._front = (self._front + 1) % self._capacity
        self._size -= 1
        return item

    def is_empty(self) -> bool:
        return self._size == 0

    def is_full(self) -> bool:
        return self._size == self._capacity


# 사용 예제
if __name__ == "__main__":
    # 기본 큐 사용
    q = Queue()
    q.enqueue("작업1")
    q.enqueue("작업2")
    q.enqueue("작업3")

    print(f"큐: {q}")              # Queue(['작업1', '작업2', '작업3'])
    print(f"front: {q.peek()}")    # 작업1
    print(f"크기: {len(q)}")        # 3

    print(f"처리: {q.dequeue()}")  # 작업1
    print(f"처리: {q.dequeue()}")  # 작업2
    print(f"남은 큐: {q}")          # Queue(['작업3'])

    # BFS 예제 - 큐 활용
    from collections import deque

    def bfs(graph, start):
        """너비 우선 탐색 - 큐 활용"""
        visited = set()
        queue = deque([start])
        result = []

        while queue:
            node = queue.popleft()
            if node not in visited:
                visited.add(node)
                result.append(node)
                queue.extend(n for n in graph[node] if n not in visited)

        return result

    graph = {
        'A': ['B', 'C'],
        'B': ['A', 'D', 'E'],
        'C': ['A', 'F'],
        'D': ['B'],
        'E': ['B', 'F'],
        'F': ['C', 'E']
    }
    print(f"BFS 순회: {bfs(graph, 'A')}")  # ['A', 'B', 'C', 'D', 'E', 'F']

🗣️ Examples of Practical Conversations

In a technical interview - Stack vs Queue comparison

"The key difference between a stack and a queue is the order in which data is processed. A stack is LIFO, so the last item in is the first one out, which makes it suitable for the function call stack and undo. A queue is FIFO, so the first item in is the first one out, and it is used for task waiting lines and BFS traversal. For example, web server request handling has to process requests in the order they arrive, so it uses a queue, while the browser back button returns to the most recent page first, so it uses a stack. In terms of time complexity, both are the same, with O(1) for insertion/deletion."

In an architecture meeting - Discussing introducing a message queue

"I think we should introduce a message queue into the order processing system. Right now, the order API calls the payment, inventory, and notification services synchronously, so if any one of them slows down, the whole response is delayed, and failures propagate when traffic spikes. If we process things asynchronously with RabbitMQ or Kafka, the order API can just put a message on the queue and respond immediately, and each service can process at its own pace. Coupling between services also decreases, and failures are isolated. However, message ordering guarantees and duplicate-processing prevention logic need to be considered separately."

During a code review - Choosing a data structure

"I think we should use a linked-list-based queue instead of array shift() in this task scheduler. shift() on a JavaScript array is O(n), so performance drops sharply as the number of elements grows. You said tens of thousands of tasks could pile up. If we build our own queue class, or implement a queue with two stacks, dequeue is possible in amortized O(1). Alternatively, there's also a way to manage a front index and process things without actually calling shift."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Queue Overflow

If you enqueue beyond capacity in a queue implemented with a fixed-size array, overflow occurs. In particular, in a plain array queue rather than a circular queue, the space at the front cannot be reused even after dequeue, so a lot of space is wasted. If dynamic resizing is needed, use a linked-list-based implementation or a deque.

2
Thread Safety

Sharing a plain queue in a multithreaded environment can cause a race condition. If multiple threads enqueue/dequeue at the same time, data loss or an infinite loop can occur. Use a thread-safe implementation such as Python's queue.Queue or Java's ConcurrentLinkedQueue, or synchronize with a lock.

3
Memory Management and Memory Leaks

In a linked-list-based queue, forgetting to free memory after removing a node causes a memory leak. Even in languages with garbage collection, if you put large objects into a queue and only dequeue them, references may remain and the objects may not be garbage collected. In message queue systems, handling the ACK (acknowledgment) of processed messages is important.

🔗 Related Terms

📚 Learn More