Implement Enqueue and Dequeue using Array-backed Queue with Fixed Size Segments
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2019-07-22
Problem Statement
Design and implement a Queue data structure that is backed by fixed-size array segments. Instead of using a single dynamically growing array, the queue must allocate chunks (segments) of fixed size to store elements. This approach helps avoid costly resizing operations and makes memory usage predictable.
✅ Functional Requirements
1.<span></span>Queue Operations
2.<span></span>enqueue(element) → Adds an element to the end of the queue.
3.<span></span>dequeue() → Removes and returns the element from the front of the queue.
4.<span></span>peek() → Returns the element at the front without removing it.
5.<span></span>isEmpty() → Returns true if the queue has no elements.
6.<span></span>Segmented Array Behavior
7.<span></span>The queue uses multiple fixed-size arrays (segments) internally.
8.<span></span>When one segment is full, allocate a new segment and link it to the previous one.
9.<span></span>When a segment becomes empty (after dequeues), it should be eligible for garbage collection or reuse.
10.<span></span>Capacity Handling
11.<span></span>Segment size should be configurable at queue initialization.
12.<span></span>Queue should dynamically grow by adding new segments as needed.
⚙️ Non-Functional Requirements
1.<span></span>Time complexity:
2.<span></span>enqueue → O(1) amortized
3.<span></span>dequeue → O(1) amortized
4.<span></span>Memory efficiency: only allocate segments when needed.
5.<span></span>Thread safety (bonus if implemented).
🔐 Constraints
1.<span></span>Segment size (e.g., 1000 elements per segment).
2.<span></span>Queue size can grow very large (e.g., up to millions of elements).
3.<span></span>Must support generic data types.
🧱 Key Classes / Methods to Model
1.<span></span>Segment
2.<span></span>Array of fixed size.
3.<span></span>Pointers to next and prev segments.
4.<span></span>Current start and end indices.
5.<span></span>SegmentedQueue
6.<span></span>enqueue(T element)
7.<span></span>T dequeue()
8.<span></span>T peek()
9.<span></span>boolean isEmpty()
🧪 Example Flow
<div><div><br /></div><div>Segment size = 3</div><div>Enqueue(10) → [10]</div><div>Enqueue(20) → [10,20]</div><div>Enqueue(30) → [10,20,30]</div><div>Enqueue(40) → new segment allocated</div><div> Segment1 = [10,20,30]</div><div> Segment2 = [40]</div><div><br /></div><div>Dequeue() → returns 10</div><div> Segment1 = [20,30]</div><div> Segment2 = [40]</div></div>👉 This LLD problem tests:
1.<span></span>Data structure design skills.
2.<span></span>Memory management with fixed-size arrays.
3.<span></span>Clean modular design (Segment vs Queue).
4.<span></span>Handling of dynamic growth without costly resizing.