3.2.7 · Coding › Linear Data Structures
Queue ek ticket counter pe line ki tarah hai: jo pehle aaya, woh pehle serve hoga — FIFO (First-In, First-Out). Aap back pe add karte ho aur front se remove karte ho, beech se kabhi nahi.
Ek queue ek linear collection hai jo do main operations support karta hai:
enqueue(x) — element x ko rear/back pe add karo.
dequeue() — front se element remove karo aur return karo.
Iska discipline hai FIFO : jo element sabse zyada wait kar raha hai woh pehle niklega.
Isko Stack (LIFO) se compare karo: stack sabse recent ko remove karta hai; queue sabse purane ko remove karta hai.
Operation
Stack (LIFO)
Queue (FIFO)
add
push (top)
enqueue (rear)
remove
pop (top)
dequeue (front)
kaun pehle niklega
newest
oldest
Bahut saare real systems ko time-order mein fairness chahiye: print jobs, CPU scheduling, graphs ka BFS traversal, web requests handle karna, keystrokes buffer karna. Agar tum newest ko pehle serve karo (stack), toh jo pehle aaye woh kabhi serve nahi hoga. FIFO guarantee karta hai ki har element eventually serve hoga, arrival order mein .
Idea: ek plain array mein front index aur rear index rakho.
enqueue: rear pe likho, phir rear++.
dequeue: front pe padho, phir front++.
Common mistake "Shifting/drifting" ka trap
Galat idea jo sahi lagta hai: "Sirf dequeue pe front ko aage badhao — simple!"
Kyun sahi lagta hai: ye hai O(1) per op aur kuch der tak kaam karta hai.
Bug: bahut saare enqueue/dequeue cycles ke baad, dono indices array ke right end ki taraf badhte jaate hain. Tum rear == capacity tak pahuncho aur naye elements ko reject kar do, chahe left side khali ho . Space waste ho jaata hai.
Fix A (slow): dequeue pe sab kuch left shift karo → O(n) per dequeue. Bura hai.
Fix B (good): indices ko wrap around karo modular arithmetic use karke — ye hai circular array .
Intuition "Circular" kyun
Socho array ka last slot uske first slot se chipka hua hai, ek ring ban raha hai. Jab rear end se bahar girti hai, woh index 0 pe wapas aa jaati hai agar woh slot free ho. Koi bhi element kabhi move nahi karta; sirf indices move hoti hain.
Wrap-around modulo se hota hai:
next ( i ) = ( i + 1 ) mod N
jahaan N capacity hai.
Hum arr[N] store karte hain, plus ek front index aur ek count (elements ki sankhya).
count kyun, rear index ki jagah? Kyunki sirf front aur rear indices se "full" aur "empty" ek jaisa dikhta hai (dono front == rear dete hain). count track karna is ambiguity ko saaf hata deta hai.
Queue ka Front arr[front] pe rehta hai.
Rear (next free slot) derive hota hai: rear = ( front + count ) mod N .
class CircularQueue :
def __init__ (self, N):
self .arr = [ None ] * N
self .N = N
self .front = 0
self .count = 0
def is_empty (self): return self .count == 0
def is_full (self): return self .count == self .N
def enqueue (self, x):
if self .is_full(): raise OverflowError ( "queue full" )
rear = ( self .front + self .count) % self .N # WHY: next free slot
self .arr[rear] = x
self .count += 1
def dequeue (self):
if self .is_empty(): raise IndexError ( "queue empty" )
x = self .arr[ self .front]
self .front = ( self .front + 1 ) % self .N # WHY: wrap front forward
self .count -= 1
return x
def peek (self):
if self .is_empty(): raise IndexError ( "queue empty" )
return self .arr[ self .front]
Chaaron core ops O(1) time mein, O(N) space mein hain. Shifting kabhi nahi.
Worked example Example 1 — basic FIFO order
Khali shuru karo, N = 5. Karo: enqueue 10, enqueue 20, enqueue 30, dequeue, dequeue.
step
front
count
rear=(f+c)%N
array (relevant)
returned
enq10
0
1
0
[10,, ,, ]
enq20
0
2
1
[10,20,, ,_]
enq30
0
3
2
[10,20,30,, ]
deq
1
2
3
front→idx1
10
deq
2
1
3
front→idx2
20
Ye step kyun (last deq): front 1 tha, humne arr[1]=20 padha, phir front=(1+1)%5=2. Humne 20 return kiya, FIFO confirm hua (10 pehle nikla, 20 se pehle). ✅
Worked example Example 2 — wrap-around (poora point yehi hai)
N = 4. Queue currently: front=2, count=2, hold kar rahi hai [_, _, A, B] (A idx2 pe, B idx3 pe).
Ab karo: enqueue(C).
rear = (front + count) % N = (2 + 2) % 4 = 0.
Ye step kyun: indices 2,3 occupied hain; next slot wrap karke 0 pe jaata hai, jo free hai. Hum arr[0] pe C rakhte hain.
Array ban jaata hai [C, _, A, B], count=3. Logical order front→rear abhi bhi A, B, C hai — physically bikhra hua, logically sahi.
Ye modulo ke bina sahi se karna impossible hai. ✅
Worked example Example 3 — full vs empty ambiguity
N = 3, sirf front/rear index, koi count nahi. Empty: front=rear=0. Ab 3 items bhar do: rear wapas 0 tak wrap ho jaata hai → front=rear=0 phir se .
Ye kyun matter karta hai: front == rear ab DONO "empty" aur "full" ka matlab deta hai. Alag karna impossible!
Fix jo hamare code mein use hua: count track karo. count==0→empty, count==N→full. Ambiguous nahi. ✅
front update pe modulo bhool jaana
Sahi lagta hai: front += 1 ek normal array walk jaisa dikhta hai.
Reality: jab front N tak pahunche, tum out of bounds index karte ho. Hamesha front = (front+1) % N likho.
front == rear ko full/empty test ki tarah use karna
Sahi lagta hai: "agar pointers milein, queue khatam."
Reality: ye full ko empty se alag nahi kar sakta. Ya toh count rakho, ya ek slot sacrifice karo (isFull ⟺ (rear+1)%N == front). Ek choose karo aur document karo .
Common mistake Queue ko stack se confuse karna
Sahi lagta hai: dono "ek cheez add aur remove karte hain." Lekin queue oldest ko remove karta hai, stack newest ko. Inhe mix karna BFS (queue chahiye) ko DFS (stack use karta hai) mein tod deta hai.
Recall Feynman: ek 12-saal ke bachche ko explain karo
Socho bachche ice cream ke liye line mein lag rahe hain. Line mein pehla bachcha pehle ice cream paata hai aur chala jaata hai; naye bachche end mein aate hain. Ye ek queue hai. Ab maano line seedhi ki jagah circle mein kursiyon ki bani ho — jab tum last kursi tak pahuncho, to agla bachcha pehli kursi pe baith jaata hai (agar woh khali ho). Woh circle trick ka matlab hai ki tum kabhi "end se bahar nahi jaate." Hum sirf yaad rakhte hain kaun si kursi pe front wala bachcha hai aur kitne bachche baithe hain .
"FIFO = First In, First Out = Friends In a Fair Order."
Ring ke liye: "Rear = Front + Count, all mod N." (Front niklega, Rear aayega, mod usse ring banaye rakhta hai.)
Enqueue aur dequeue kahaan hote hain?
Plain array queue space waste kyun karta hai, aur circular use kaise fix karta hai?
Front aur count diye hone pe rear index ka formula kya hai?
front == rear compare karne ki jagah count kyun prefer karein?
Queue kaun sa discipline follow karta hai? FIFO — First In, First Out (sabse purana element pehle niklega).
Queue mein enqueue aur dequeue kahaan hote hain? Enqueue rear/back pe; dequeue front se.
Naïve (non-circular) array queue space-inefficient kyun hai? front aur rear daayein taraf drift karte hain; jab rear capacity tak pahunche toh queue "full" lagta hai chahe left slots khali hon.
Circular queue mein wrap-around kaun sa math operation enable karta hai? Modulo: index = (index + 1) % N.
Front aur count use karke next free (rear) slot ka formula? rear = (front + count) % N.
Dequeue ke baad naya front kaise compute karte hain? front = (front + 1) % N.
Sirf front aur rear indices ki jagah count kyun track karte hain? Kyunki front == rear ambiguous hai (dono empty aur full ka matlab deta hai); count empty (0) vs full (N) ko unambiguous banata hai.
Circular array mein enqueue aur dequeue ki time complexity? O(1) each — sirf indices move hoti hain, shifting nahi.
Queue empty ki condition (count ke saath)? count == 0.
Queue full ki condition (count ke saath, capacity N)? count == N.
Queue vs Stack: pehle kaun remove hota hai? Queue oldest ko remove karta hai (FIFO); Stack newest ko remove karta hai (LIFO).
Kaun sa traversal queue use karta hai: BFS ya DFS? BFS (Breadth-First Search) queue use karta hai; DFS stack use karta hai.
Stack — LIFO (mirror image: newest-first vs oldest-first)
Modular Arithmetic (woh % N jo ring banata hai)
Breadth-First Search (BFS) (queue ka canonical user)
Deque — Double-Ended Queue (generalization: dono ends pe add/remove)
Circular Buffer / Ring Buffer (OS aur networking mein same structure)
Amortized Analysis (linked-list queue se compare karo, koi resize cost nahi)
Priority Queue (FIFO tod deta hai: arrival ki jagah priority se order)
Fairness in arrival order
BFS, CPU scheduling, buffers
Naive array with front and rear
Circular array ring buffer