← Google bank

Google · Question 47 · Queues

Implement Circular Queue

QueuesPythoncode⏱ O(1)💾 O(k)
Product-based

Problem

Design a circular queue supporting enqueue, dequeue, front, rear, and empty operations.

Approach

Use a fixed-size array with pointers.

Time O(1)Space O(k)

How it works

  1. 1Use an array and two pointers for front and rear.
  2. 2Wrap pointers using modulo for circularity.
  3. 3Check the full condition when next rear equals front.
  4. 4Handle the empty condition when pointers reset.

Sample input / output

Input:
3 9
enQueue 1
enQueue 2
enQueue 3
enQueue 4
Rear
isFull
deQueue
enQueue 4
Rear
Output:
[True, True, True, False, 3, True, True, True, 4]

Constraints

1 <= k <= 1000; 0 <= value <= 1000; at most 3000 calls total.

Solution — read it, then walk it

Time O(1)Space O(k)Loops 1Branches 9Returns 8source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesnoyesnoyesno↻ repeatSTARTCLASS MyCircularQueueDEFINE __init__(self, k)self.queue = [0] * kself.head = self.tail = -1self.size = kDEFINE enQueue(self, value)if self.isFull()RETURN Falseif self.isEmpty()self.head = 0self.tail = (self.tail + 1)% self.sizeself.queue[self.tail] =valueRETURN TrueDEFINE deQueue(self)if self.isEmpty()RETURN Falseif self.head ==self.tailself.head = self.tail = -1ELSEself.head = (self.head + 1)% self.sizeRETURN TrueDEFINE Front(self)RETURN -1 if self.isEmpty()else self.queue[self.head]DEFINE Rear(self)RETURN -1 if self.isEmpty()else self.queue[self.tail]DEFINE isEmpty(self)RETURN self.head == -1DEFINE isFull(self)RETURN (self.tail + 1) %self.size == self.headDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)k = int(next(it)); ops =int(next(it))q = MyCircularQueue(k)out = []for _ in range(ops)op = next(it)if op == 'enQueue'out.append(q.enQueue(int(next(it))))elif op == 'deQueue'out.append(q.deQueue())elif op == 'Rear'out.append(q.Rear())elif op == 'Front'
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits