Problem 622

Abstract / Summary

Design a circular queue that supports adding removing and checking elements with a fixed size.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0622.py

lass MyCircularQueue:
    def pos(self, i):
        while i < 0:
            i += self.capacity
        if i >= self.capacity:
            i = i % self.capacity
        return i

    def diff(self, posA, posB):
        return self.pos(posB - posA)

    def __init__(self, k: int):
        self.first = 0
        self.last  = 0
        self.size  = 0
        self.capacity = k
        self.data  = dict()

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        self.data[self.last] = value
        self.last += 1
        self.size += 1
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        self.first += 1
        self.size  -= 1
        return True

    def Front(self) -> int:
        if self.isEmpty():
            return -1
        return self.data[self.first]

    def Rear(self) -> int:
        if self.isEmpty():
            return -1
        return self.data[self.last - 1]

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

    def isFull(self) -> bool:
        return self.size == self.capacity
48 lines | 1169 bytes | submitted August 14, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (900k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Linked List
  • Queue
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a circular queue data structure with a fixed capacity. It maintains logical pointers to the front (first) and the position where the next element will be inserted (last). The queue tracks its current element count (size) and stores values in a dictionary keyed by their logical position. Core operations-enqueue, dequeue, and queries for the front and rear elements-are implemented with constant-time checks for emptiness and fullness.

Core Methods and Their Logic

The pos method normalizes any integer index to a valid position within the circular buffer. It repeatedly adds the capacity while the index is negative, then reduces any overflow by applying the modulo operator. This ensures that both positive and negative offsets are correctly wrapped around the underlying storage range.

def pos(self, i):
    while i < 0:
        i += self.capacity
    if i >= self.capacity:
        i = i % self.capacity
    return i

The diff method computes the distance from one logical position to another by delegating to pos. It effectively returns the number of steps required to move from posA to posB within the circular layout.

def diff(self, posA, posB):
    return self.pos(posB - posA)

Construction initializes the queue with zero elements, sets the capacity, and creates an empty dictionary for storage. The first and last pointers both start at zero, representing an empty state.

def __init__(self, k: int):
    self.first = 0
    self.last  = 0
    self.size  = 0
    self.capacity = k
    self.data  = dict()

The enQueue operation first checks whether the queue is full. If not, it stores the new value at the current last index, increments last, and updates size. The method returns a boolean indicating success.

def enQueue(self, value: int) -> bool:
    if self.isFull():
        return False
    self.data[self.last] = value
    self.last += 1
    self.size += 1
    return True

The deQueue operation mirrors enQueue. It verifies that the queue is not empty, then advances the first pointer and decrements size. No element is physically removed from the dictionary; the logical view of the queue simply moves forward.

def deQueue(self) -> bool:
    if self.isEmpty():
        return False
    self.first += 1
    self.size  -= 1
    return True

The Front method returns the element at the logical front of the queue. When the queue is empty, it yields -1 as a sentinel value.

def Front(self) -> int:
    if self.isEmpty():
        return -1
    return self.data[self.first]

The Rear method retrieves the most recently enqueued element. It calculates the index of the last element as self.last - 1. If the queue is empty, it also returns -1.

def Rear(self) -> int:
    if self.isEmpty():
        return -1
    return self.data[self.last - 1]

The isEmpty and isFull helpers compare the current size against zero and the configured capacity, respectively. Both checks are simple integer comparisons.

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

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

Edge Cases Handled by the Implementation

When the queue reaches its maximum capacity, enQueue detects the full condition via isFull and refuses to add more elements, returning False. Conversely, attempting to remove an element from an empty queue triggers isEmpty inside deQueue, causing the method to return False without altering internal state.

The Front and Rear methods both guard against empty queues by checking isEmpty. In such cases they return -1, providing a clear indicator that no valid element exists at the requested position.

The pos method safeguards against negative indices that could arise from arithmetic on first or last. By looping until the index becomes non-negative and then applying modulo reduction, it guarantees that any computed position maps to a valid slot within the fixed capacity. This normalization also protects against overflow when last or first grow beyond the capacity due to repeated enqueue or dequeue operations.

Performance Optimizations Present in the Code

The design stores elements in a dictionary keyed by their logical index rather than a fixed-size list. This choice eliminates the need to pre-allocate a list of length capacity and allows direct O(1) access to any element via its key. The dictionary also avoids shifting elements on dequeue, because the logical view moves forward while the underlying storage remains untouched.

Maintaining an explicit size counter eliminates the need to compute the number of elements by subtracting pointers or iterating over the dictionary. Consequently, isEmpty and isFull are simple integer comparisons that execute in constant time.

The pos method performs normalization only when necessary. It first resolves negative offsets through a loop that adds the capacity, which is efficient for small negative values. For positive overflow, it applies a single modulo operation. By centralizing this logic, the rest of the queue operations avoid repeated modulo calculations, reducing overhead during frequent enqueue and dequeue calls.

Incrementing first and last without immediate wrapping (i.e., without applying modulo on each increment) defers the normalization cost to the point where an index is actually used for storage or retrieval. This lazy wrapping strategy minimizes arithmetic work during the high-frequency path of adding or removing elements.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a magical toy train that travels in a perfect circle. This code creates the train and decides where to park the cars.

The part called pos acts like a compass. If the train tries to go off the track, this code guides it back to the right spot on the circle.

The diff part simply figures out how much space is between two cars by measuring around the circle.

Inside the init function, the train starts out completely empty. It has a set amount of space for how many cars can fit at once.

When a new car arrives to join the line in the enQueue part, the train first checks if there is any room left. If it is full, it says no. If there is space, the new car finds its place at the end of the line.

When a car leaves the line in the deQueue part, the train checks to see if anyone is still waiting. If the train is empty, it says nothing can happen. If there is someone there, the car at the very front zooms away, and the line gets shorter.

Front and Rear are just ways to peek at who is waiting. Front looks at the car at the beginning of the line, and Rear looks at the car that just joined at the end.

Finally, isEmpty and isFull are like little signs. One sign lights up when the train is totally empty, and the other sign lights up when every single seat is taken.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.50 | σ = 1.84

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
37 links | 23 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

20 solutions   August 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality