홈/알고리즘/[코딩테스트] 원형 큐 설계

[코딩테스트] 원형 큐 설계

배열을 사용하여 원형 큐의 삽입, 삭제, 조회 연산을 구현하는 방법입니다.

문제

원형 큐(Circular Queue)는 선형 데이터 구조로, FIFO(First In First Out) 원칙에 따라 동작하며 마지막 위치가 첫 번째 위치와 연결되어 고리 형태를 이룹니다. 이를 '링 버퍼(Ring Buffer)'라고도 부릅니다. 일반 큐는 가득 찼을 때 앞쪽의 빈 공간을 활용할 수 없지만, 원형 큐는 이 공간을 재사용하여 새로운 값을 저장할 수 있습니다.

구현해야 할 MyCircularQueue 클래스의 메서드는 다음과 같습니다.

  • MyCircularQueue(k): 크기가 k인 큐를 초기화합니다.
  • Front(): 큐의 앞쪽 요소를 반환합니다. 비어 있으면 -1을 반환합니다.
  • Rear(): 큐의 뒤쪽 요소를 반환합니다. 비어 있으면 -1을 반환합니다.
  • enQueue(int value): 요소를 삽입합니다. 성공 시 true, 실패(큐가 가득 참) 시 false를 반환합니다.
  • deQueue(): 요소를 삭제합니다. 성공 시 true, 실패(큐가 비어 있음) 시 false를 반환합니다.
  • isEmpty(): 큐가 비어 있는지 확인합니다.
  • isFull(): 큐가 가득 찼는지 확인합니다.

내장 큐 자료구조를 사용하지 않고 구현해야 합니다.

접근 방법

고정된 크기의 배열을 사용하여 원형 큐를 구현합니다. 배열의 인덱스를 순환시키기 위해 모듈로 연산자(%)를 활용합니다. 큐의 상태를 관리하기 위해 두 개의 포인터와 카운터를 사용합니다.

  • head: 큐의 앞쪽 요소를 가리키는 인덱스입니다.
  • tail: 다음 요소가 삽입될 위치를 가리키는 인덱스입니다.
  • count: 현재 큐에 저장된 요소의 개수를 나타냅니다.

초기화 시 배열 크기를 k로 설정하고, head와 tail을 0으로, count를 0으로 초기화합니다.

  • 삽입(enQueue): count가 k보다 작을 때만 수행합니다. tail 위치에 값을 저장한 후 tail을 (tail + 1) % k로 이동시키고 count를 증가시킵니다.
  • 삭제(deQueue): count가 0보다 클 때만 수행합니다. head를 (head + 1) % k로 이동시키고 count를 감소시킵니다.
  • 조회(Front, Rear): count가 0인지 확인한 후, head 또는 (tail - 1 + k) % k 인덱스의 값을 반환합니다.

풀이

배열 기반 원형 큐를 구현한 코드입니다. 모든 연산은 상수 시간 O(1)에 수행됩니다.

class MyCircularQueue:

    def __init__(self, k: int):
        """
        큐의 크기를 k로 설정하고 배열을 초기화합니다.
        """
        self.queue = [0] * k
        self.head = 0
        self.tail = 0
        self.count = 0
        self.size = k

    def enQueue(self, value: int) -> bool:
        """
        큐에 요소를 삽입합니다.
        """
        if self.isFull():
            return False
        self.queue[self.tail] = value
        self.tail = (self.tail + 1) % self.size
        self.count += 1
        return True

    def deQueue(self) -> bool:
        """
        큐에서 요소를 삭제합니다.
        """
        if self.isEmpty():
            return False
        self.head = (self.head + 1) % self.size
        self.count -= 1
        return True

    def Front(self) -> int:
        """
        큐의 앞쪽 요소를 반환합니다.
        """
        if self.isEmpty():
            return -1
        return self.queue[self.head]

    def Rear(self) -> int:
        """
        큐의 뒤쪽 요소를 반환합니다.
        """
        if self.isEmpty():
            return -1
        # tail은 다음 삽입 위치이므로, 실제 마지막 요소는 tail - 1 위치입니다.
        # 음수 인덱스 처리를 위해 (tail - 1 + self.size) % self.size를 사용합니다.
        return self.queue[(self.tail - 1 + self.size) % self.size]

    def isEmpty(self) -> bool:
        """
        큐가 비어 있는지 확인합니다.
        """
        return self.count == 0

    def isFull(self) -> bool:
        """
        큐가 가득 찼는지 확인합니다.
        """
        return self.count == self.size

# Helper to validate the same public operation sequence used by the problem.
def exercise_array_queue(operations, arguments):
    queue = None
    results = []
    for operation, params in zip(operations, arguments):
        if operation == "MyCircularQueue":
            queue = MyCircularQueue(*params)
            results.append(None)
        elif operation == "enQueue":
            results.append(queue.enQueue(*params))
        elif operation == "deQueue":
            results.append(queue.deQueue(*params))
        elif operation == "Front":
            results.append(queue.Front(*params))
        elif operation == "Rear":
            results.append(queue.Rear(*params))
        elif operation == "isEmpty":
            results.append(queue.isEmpty(*params))
        elif operation == "isFull":
            results.append(queue.isFull(*params))
        else:
            raise ValueError("Unsupported circular queue operation")
    return results
  • 시간 복잡도: 모든 메서드(enQueue, deQueue, Front, Rear, isEmpty, isFull)는 상수 시간 O(1)에 동작합니다.
  • 공간 복잡도: 고정 크기 배열을 사용하므로 O(k)입니다.

다른 풀이 방법

단일 연결 리스트로도 원형 큐를 구현할 수 있습니다. head는 맨 앞 노드, tail은 맨 뒤 노드를 가리키며, 큐가 비어 있지 않을 때는 항상 tail.next = head가 되도록 유지합니다. count로 용량 초과 여부를 확인합니다.

class CircularQueueNode:
    def __init__(self, value):
        self.value = value
        self.next = None

class MyCircularQueueLinked:
    def __init__(self, k: int):
        self.capacity = k
        self.head = None
        self.tail = None
        self.count = 0

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        node = CircularQueueNode(value)
        if self.isEmpty():
            self.head = self.tail = node
            node.next = node
        else:
            node.next = self.head
            self.tail.next = node
            self.tail = node
        self.count += 1
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        if self.count == 1:
            self.head = self.tail = None
        else:
            self.head = self.head.next
            self.tail.next = self.head
        self.count -= 1
        return True

    def Front(self) -> int:
        return -1 if self.isEmpty() else self.head.value

    def Rear(self) -> int:
        return -1 if self.isEmpty() else self.tail.value

    def isEmpty(self) -> bool:
        return self.count == 0

    def isFull(self) -> bool:
        return self.count == self.capacity

def exercise_linked_queue(operations, arguments):
    queue = None
    results = []
    for operation, params in zip(operations, arguments):
        if operation == "MyCircularQueue":
            queue = MyCircularQueueLinked(*params)
            results.append(None)
        elif operation == "enQueue":
            results.append(queue.enQueue(*params))
        elif operation == "deQueue":
            results.append(queue.deQueue(*params))
        elif operation == "Front":
            results.append(queue.Front(*params))
        elif operation == "Rear":
            results.append(queue.Rear(*params))
        elif operation == "isEmpty":
            results.append(queue.isEmpty(*params))
        elif operation == "isFull":
            results.append(queue.isFull(*params))
        else:
            raise ValueError("Unsupported circular queue operation")
    return results

삽입과 삭제, 앞·뒤 조회는 모두 포인터와 카운터만 갱신하므로 O(1)입니다. 노드가 최대 k개 생성되므로 공간 복잡도는 O(k)입니다. 배열 기반 구현과 달리 각 노드를 동적으로 할당하는 오버헤드가 있지만, 고정 배열 대신 노드 단위로 저장하는 구조를 이해할 수 있는 대안입니다.

추가 참고사항

  • 모듈로 연산자 %는 인덱스가 배열의 경계를 넘어갈 때 다시 0으로 돌아가도록 하는 핵심 기법입니다.
  • Rear() 메서드에서 tail 인덱스는 다음 삽입 위치를 가리키므로, 실제 마지막 요소의 인덱스는 (tail - 1 + size) % size로 계산해야 합니다. tail이 0일 때 -1이 되는 경우를 처리하기 위해 size를 더한 후 모듈로 연산을 수행합니다.
  • 이 문제는 자료구조의 기본 원리를 이해하고 배열의 인덱스 조작 능력을 평가하는 데 중점을 둡니다.

출처

END OF NOTE

읽다가 궁금한 코드를 직접 실행해 보세요.

작은 실험이 이해를 도와줄 수 있어요.