Queue and Deque Data Structures Exercise - Complete Solutions
Data Structures - Queue and Deque Operations
1
Question 1: Fill in the Blanks
a) _____________ is a linear list of elements in which insertion and deletion takes place from different ends.
b) Operations on a queue are performed in _____________ order.
c) Insertion operation in a queue is called _____________ and deletion operation in a queue is called _____________.
d) Deletion of elements is performed from _____________ end of the queue.
e) Elements 'A', 'S', 'D' and 'F' are present in the queue, and they are deleted one at a time, _____________ is the sequence of element received.
f) _____________ is a data structure where elements can be added or removed at either end, but not in the middle.
g) A deque contains 'z', 'x', 'c', 'v' and 'b'. Elements received after deletion are 'z', 'b', 'v', 'x' and 'c'. _____________ is the sequence of deletion operation performed on deque.
Answer 1
a) Queue is a linear list of elements in which insertion and deletion takes place from different ends.
b) Operations on a queue are performed in FIFO (First In First Out) order.
c) Insertion operation in a queue is called enqueue and deletion operation in a queue is called dequeue.
d) Deletion of elements is performed from front end of the queue.
e) Elements 'A', 'S', 'D' and 'F' are present in the queue, and they are deleted one at a time, A, S, D, F is the sequence of element received.
f) Deque (Double-ended queue) is a data structure where elements can be added or removed at either end, but not in the middle.
g) A deque contains 'z', 'x', 'c', 'v' and 'b'. Elements received after deletion are 'z', 'b', 'v', 'x' and 'c'. deleteFront(), deleteRear(), deleteRear(), deleteFront(), deleteFront() is the sequence of deletion operation performed on deque.
2
Question 2: Compare and Contrast Queue with Stack
Compare and contrast queue with stack.
Answer 2
| Aspect | Queue | Stack |
|---|---|---|
| Principle | FIFO (First In First Out) | LIFO (Last In First Out) |
| Insertion | At rear/back end | At top only |
| Deletion | From front end | From top only |
| Operations | enqueue(), dequeue(), front(), isEmpty() | push(), pop(), top(), isEmpty() |
| Real-world Examples | Printer queue, CPU scheduling, BFS | Function calls, Undo operations, DFS |
| Access Pattern | Two-ended access (front and rear) | Single-ended access (top only) |
| Memory Usage | Requires front and rear pointers | Requires only top pointer |
3
Question 3: How does FIFO describe queue?
How does FIFO describe queue?
Answer 3
FIFO (First In First Out) perfectly describes the queue data structure because:
- First In: The first element added to the queue is the first one to be removed
- Sequential Processing: Elements are processed in the exact order they were inserted
- Two-End Operations: Insertion happens at the rear (back) and deletion happens at the front
- No Random Access: You cannot access elements in the middle; only the front element can be accessed
FIFO Visualization:
Initial Queue: [A, B, C, D]
When dequeue() is called, 'A' is removed first (FIFO principle)
Real-world FIFO Examples:
- People waiting in line at a bank or store
- Print jobs in a printer queue
- Processes waiting for CPU time in operating systems
- Breadth-First Search (BFS) algorithm in graphs
- Handling requests in web servers
4
Question 4: Menu Driven Python Program - Shuttlecock Movement
Write a menu driven python program using queue, to implement movement of shuttlecock in it's box.
Answer 4
Here's a menu-driven Python program that simulates shuttlecock movement in a box using queue:
from collections import deque
class ShuttlecockBox:
def __init__(self, capacity=10):
self.box = deque()
self.capacity = capacity
self.shuttlecock_count = 0
def add_shuttlecock(self, shuttlecock_id):
"""Add a shuttlecock to the box (enqueue)"""
if len(self.box) >= self.capacity:
print(f"Box is full! Cannot add shuttlecock {shuttlecock_id}")
return False
self.box.append(shuttlecock_id)
self.shuttlecock_count += 1
print(f"Shuttlecock {shuttlecock_id} added to the box")
return True
def remove_shuttlecock(self):
"""Remove a shuttlecock from the box (dequeue)"""
if not self.box:
print("Box is empty! No shuttlecock to remove")
return None
removed = self.box.popleft()
print(f"Shuttlecock {removed} removed from the box")
return removed
def peek(self):
"""View the next shuttlecock to be removed"""
if not self.box:
print("Box is empty!")
return None
print(f"Next shuttlecock to be removed: {self.box[0]}")
return self.box[0]
def display_box(self):
"""Display current state of the box"""
if not self.box:
print("Box is empty!")
else:
print(f"Current shuttlecocks in box: {list(self.box)}")
print(f"Total shuttlecocks: {len(self.box)}")
def is_empty(self):
"""Check if box is empty"""
return len(self.box) == 0
def is_full(self):
"""Check if box is full"""
return len(self.box) >= self.capacity
def main():
box = ShuttlecockBox()
while True:
print("\n" + "="*50)
print("SHUTTLECOCK BOX MANAGEMENT SYSTEM")
print("="*50)
print("1. Add Shuttlecock to Box")
print("2. Remove Shuttlecock from Box")
print("3. Peek Next Shuttlecock")
print("4. Display Box Contents")
print("5. Check if Box is Empty")
print("6. Check if Box is Full")
print("7. Simulate Game (Add multiple shuttlecocks)")
print("8. Exit")
print("="*50)
try:
choice = int(input("Enter your choice (1-8): "))
if choice == 1:
shuttlecock_id = input("Enter shuttlecock ID: ")
box.add_shuttlecock(shuttlecock_id)
elif choice == 2:
box.remove_shuttlecock()
elif choice == 3:
box.peek()
elif choice == 4:
box.display_box()
elif choice == 5:
if box.is_empty():
print("Box is empty!")
else:
print("Box is not empty!")
elif choice == 6:
if box.is_full():
print("Box is full!")
else:
print(f"Box has space for {box.capacity - len(box.box)} more shuttlecocks")
elif choice == 7:
print("Simulating a badminton game...")
shuttlecocks = ["S1", "S2", "S3", "S4", "S5"]
for s in shuttlecocks:
box.add_shuttlecock(s)
print("\nGame started! Using shuttlecocks in FIFO order:")
while not box.is_empty():
used = box.remove_shuttlecock()
print(f"Playing with shuttlecock {used}")
elif choice == 8:
print("Thank you for using Shuttlecock Box Management System!")
break
else:
print("Invalid choice! Please enter a number between 1-8.")
except ValueError:
print("Invalid input! Please enter a valid number.")
except KeyboardInterrupt:
print("\n\nProgram interrupted by user. Goodbye!")
break
if __name__ == "__main__":
main()Program Features:
- Queue-based shuttlecock management using FIFO principle
- Add shuttlecocks to the box (enqueue operation)
- Remove shuttlecocks from the box (dequeue operation)
- Peek functionality to view next shuttlecock
- Box capacity management
- Game simulation feature
- Error handling for invalid inputs
5
Question 5: Queue vs Deque Data Types
How is queue data type different from deque data type?
Answer 5
| Feature | Queue | Deque (Double-ended Queue) |
|---|---|---|
| Full Form | Queue | Double-ended Queue |
| Insertion | Only at rear end | At both front and rear ends |
| Deletion | Only from front end | From both front and rear ends |
| Operations | enqueue(), dequeue(), front(), isEmpty() | insertFront(), insertRear(), deleteFront(), deleteRear() |
| Flexibility | Limited - strict FIFO | High - can work as stack or queue |
| Access Pattern | FIFO only | FIFO, LIFO, or mixed patterns |
| Implementation | Simpler implementation | More complex implementation |
| Memory Usage | Less memory overhead | Slightly more memory overhead |
| Use Cases | BFS, CPU scheduling, Print queues | Palindrome checking, Sliding window, Browser history |
Key Differences Summary:
- Queue: Restricted to one-way insertion and deletion (FIFO principle)
- Deque: Allows insertion and deletion at both ends, making it more versatile
- Deque can simulate both Queue and Stack: Use insertRear() and deleteFront() for queue behavior, or insertRear() and deleteRear() for stack behavior
- Performance: Both have O(1) time complexity for basic operations
6
Question 6: Queue Status After Operations
Show the status of queue after each operation:
Answer 6
Step-by-step Queue Operations:
Initial: Queue = []
enqueue(34): Queue = [34]
enqueue(54): Queue = [34, 54]
dequeue(): Removed 34, Queue = [54]
enqueue(12): Queue = [54, 12]
dequeue(): Removed 54, Queue = [12]
enqueue(61): Queue = [12, 61]
peek(): Front element is 12, Queue = [12, 61]
dequeue(): Removed 12, Queue = [61]
dequeue(): Removed 61, Queue = []
dequeue(): Error - Queue is empty!
dequeue(): Error - Queue is empty!
enqueue(1): Queue = [1]
Final Queue State: [1]
Note: Dequeue operations on an empty queue result in underflow errors in practical implementations.
7
Question 7: Deque Status After Operations
Show the status of deque after each operation:
Answer 7
Step-by-step Deque Operations:
Initial: Deque = []
peek(): Error - Deque is empty!
insertFront(12): Deque = [12]
Front: 12, Rear: 12
insertRear(67): Deque = [12, 67]
Front: 12, Rear: 67
deletionFront(): Removed 12, Deque = [67]
Front: 67, Rear: 67
insertRear(43): Deque = [67, 43]
Front: 67, Rear: 43
deletionRear(): Removed 43, Deque = [67]
Front: 67, Rear: 67
deletionFront(): Removed 67, Deque = []
deletionRear(): Error - Deque is empty!
Final Deque State: [] (Empty)
Note: Deque allows insertion and deletion from both ends, providing more flexibility than a regular queue.
8
Question 8: Palindrome Checker Using Deque
Write a python program to check whether the given string is palindrome or not, using deque. (Hint: refer to algorithm 4.1)
Answer 8
Here's a Python program to check if a string is a palindrome using deque:
from collections import deque
def is_palindrome_deque(s):
"""
Check if a string is palindrome using deque
Algorithm 4.1: Palindrome Checker
Steps:
1. Remove spaces and convert to lowercase
2. Add all characters to deque
3. Compare characters from both ends
4. Remove matching characters from both ends
5. Continue until deque is empty or mismatch found
"""
# Preprocessing: remove spaces and convert to lowercase
cleaned_string = ''.join(s.split()).lower()
# Create deque and add all characters
char_deque = deque(cleaned_string)
# Check palindrome by comparing front and rear characters
while len(char_deque) > 1:
front_char = char_deque.popleft() # Remove from front
rear_char = char_deque.pop() # Remove from rear
if front_char != rear_char:
return False
return True
def is_palindrome_advanced(s):
"""
Advanced palindrome checker with more preprocessing
Handles punctuation, spaces, and case sensitivity
"""
# Remove non-alphanumeric characters and convert to lowercase
cleaned = ''.join(char.lower() for char in s if char.isalnum())
# Create deque
char_deque = deque(cleaned)
# Check palindrome
while len(char_deque) > 1:
if char_deque.popleft() != char_deque.pop():
return False
return True
def demonstrate_palindrome_checking():
"""Demonstrate palindrome checking with various examples"""
test_strings = [
"racecar",
"A man a plan a canal Panama",
"race a car",
"hello",
"Madam",
"Was it a car or a cat I saw",
"No 'x' in Nixon",
"Mr. Owl ate my metal worm",
"12321",
"12345"
]
print("PALINDROME CHECKER USING DEQUE")
print("=" * 50)
for test_string in test_strings:
result_basic = is_palindrome_deque(test_string)
result_advanced = is_palindrome_advanced(test_string)
print(f"String: '{test_string}'")
print(f" Basic Check: {'✓ Palindrome' if result_basic else '✗ Not Palindrome'}")
print(f" Advanced Check: {'✓ Palindrome' if result_advanced else '✗ Not Palindrome'}")
print()
def interactive_palindrome_checker():
"""Interactive palindrome checker"""
print("\nINTERACTIVE PALINDROME CHECKER")
print("=" * 40)
while True:
user_input = input("\nEnter a string to check (or 'quit' to exit): ")
if user_input.lower() == 'quit':
break
# Show deque operations step by step
print(f"\nChecking: '{user_input}'")
cleaned = ''.join(user_input.split()).lower()
print(f"Cleaned string: '{cleaned}'")
char_deque = deque(cleaned)
print(f"Initial deque: {list(char_deque)}")
is_palindrome = True
step = 1
while len(char_deque) > 1:
front = char_deque.popleft()
rear = char_deque.pop()
print(f"Step {step}: Comparing '{front}' (front) with '{rear}' (rear)")
if front != rear:
print(f" ✗ Mismatch found! Not a palindrome.")
is_palindrome = False
break
else:
print(f" ✓ Match! Remaining deque: {list(char_deque)}")
step += 1
if is_palindrome:
print(f" 🎉 '{user_input}' is a PALINDROME!")
else:
print(f" ❌ '{user_input}' is NOT a palindrome.")
# Algorithm 4.1 Implementation
def palindrome_algorithm_4_1(string):
"""
Implementation of Algorithm 4.1 for Palindrome Checking
Algorithm 4.1: Palindrome Checker using Deque
Input: String to check
Output: Boolean (True if palindrome, False otherwise)
Steps:
1. Initialize empty deque
2. Process string (remove spaces, convert to lowercase)
3. Insert all characters into deque
4. While deque has more than one character:
a. Remove character from front
b. Remove character from rear
c. If characters don't match, return False
5. Return True (palindrome confirmed)
"""
# Step 1: Initialize deque
dq = deque()
# Step 2: Process string
processed_string = ''.join(string.split()).lower()
# Step 3: Insert all characters
for char in processed_string:
dq.append(char)
# Step 4: Compare characters from both ends
while len(dq) > 1:
front_char = dq.popleft() # Remove from front
rear_char = dq.pop() # Remove from rear
if front_char != rear_char:
return False
# Step 5: String is palindrome
return True
def main():
"""Main function to run palindrome checker"""
print("PALINDROME CHECKER USING DEQUE")
print("Based on Algorithm 4.1")
print("=" * 50)
# Demonstrate with predefined examples
demonstrate_palindrome_checking()
# Interactive checker
interactive_palindrome_checker()
print("\nThank you for using the Palindrome Checker!")
if __name__ == "__main__":
main()Algorithm 4.1 - Palindrome Checker Logic:
- Preprocessing: Clean the string by removing spaces and converting to lowercase
- Initialize Deque: Create an empty deque and add all characters
- Comparison Loop: While deque has more than one character:
- Remove character from front (popleft())
- Remove character from rear (pop())
- Compare both characters
- If they don't match, return False
- Result: If loop completes without mismatch, string is palindrome
Example Execution:
Input: "racecar"
Initial deque: ['r', 'a', 'c', 'e', 'c', 'a', 'r']
Step 1: Compare 'r' and 'r' → Match, deque: ['a', 'c', 'e', 'c', 'a']
Step 2: Compare 'a' and 'a' → Match, deque: ['c', 'e', 'c']
Step 3: Compare 'c' and 'c' → Match, deque: ['e']
Result: Palindrome confirmed! ✓
Key Concepts Summary
Queue Properties:
- FIFO (First In First Out) principle
- Insertion at rear, deletion from front
- Linear data structure
- Operations: enqueue, dequeue, peek
Deque Properties:
- Double-ended queue
- Insertion/deletion at both ends
- More flexible than regular queue
- Can simulate both stack and queue
Applications and Real-World Examples
Queue Applications:
- CPU task scheduling in operating systems
- Print job management in printers
- Breadth-First Search (BFS) in graphs
- Handling requests in web servers
- Call center systems
- Buffer for data streams
Deque Applications:
- Palindrome checking algorithms
- Sliding window maximum problems
- Browser history implementation
- Undo/Redo operations
- A-Steal job scheduling algorithm
- Implementing both stack and queue
Time Complexity Analysis:
Queue Operations:
- Enqueue: O(1)
- Dequeue: O(1)
- Peek/Front: O(1)
- isEmpty: O(1)
Deque Operations:
- insertFront/insertRear: O(1)
- deleteFront/deleteRear: O(1)
- getFront/getRear: O(1)
- isEmpty: O(1)

