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
Difficulty
and has an acceptance rate of about 55% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Linked List
- Queue
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 641: Design Circular Deque
- problem 1670: Design Front Middle Back Queue
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
Extra
- 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