← Meta (Facebook) bank

Meta (Facebook) · Question 31 · Queues

Design Circular Queue

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

Problem

You are required to implement a circular queue with fixed size.

Approach

Track front, rear, size and capacity; wrap indices with modulo.

Time O(1)Space O(k)

How it works

  1. 1Keep front, size and capacity; derive rear by modulo.
  2. 2Size alone answers full/empty checks.
  3. 3All operations stay O(1).

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; <= 3000 calls.

Solution — read it, then walk it

Time O(1)Space O(k)Loops 1Branches 6Returns 8source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesnoyes↻ repeat↻ repeatSTARTCLASS MyCircularQueueDEFINE __init__(self, k)self.data = [0] * kself.front = 0self.rear = -1self.size = 0self.capacity = kDEFINE enQueue(self, value)if self.isFull()RETURN Falseself.rear = (self.rear + 1)% self.capacityself.data[self.rear] =valueself.size += 1RETURN TrueDEFINE deQueue(self)if self.isEmpty()RETURN Falseself.front = (self.front +1) % self.capacityself.size -= 1RETURN TrueDEFINE Front(self)RETURN -1 if self.isEmpty()else self.data[self.front]DEFINE Rear(self)RETURN -1 if self.isEmpty()else self.data[self.rear]DEFINE isEmpty(self)RETURN self.size == 0DEFINE isFull(self)RETURN self.size ==self.capacityDEFINE 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'out.append(q.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