← Uber bank

Uber · Question 33 · Queues

Implement Circular Queue

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

Problem

Design a circular queue with fixed capacity supporting enqueue, dequeue, front, rear, isEmpty, and isFull operations.

Approach

Use a fixed-size list, a head pointer, and a count of elements. Tail is computed via modular arithmetic.

Time O(1)Space O(k)

How it works

  1. 1Track head, count and capacity; derive tail by modulo.
  2. 2Enqueue at the tail unless full; dequeue advances head.
  3. 3Front/Rear read by position; full/empty compare counts.

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 9source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesnoyes↻ repeat↻ repeatSTARTCLASS MyCircularQueueDEFINE __init__(self, k:int)self.queue = [0] * kself.head = 0self.count = 0self.capacity = kDEFINE enQueue(self, value:int) -> boolif self.count ==self.capacityRETURN Falsetail = (self.head +self.count) % self.capacityself.queue[tail] = valueself.count += 1RETURN TrueDEFINE deQueue(self) ->boolif self.count == 0RETURN Falseself.head = (self.head + 1)% self.capacityself.count -= 1RETURN TrueDEFINE Front(self) -> intRETURNself.queue[self.head] ifself.count != 0 else -1DEFINE Rear(self) -> intif self.count == 0RETURN -1tail = (self.head +self.count - 1) %self.capacityRETURN self.queue[tail]DEFINE isEmpty(self) ->boolRETURN self.count == 0DEFINE isFull(self) -> boolRETURN self.count ==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())
  • 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