Table of Contents
What is a Stack? (Think Plates)
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that the most recently added element is always the first one to be removed.Key Operations
- Push Operation: The push operation inserts a new element at the top of the stack.
- Pop Operation: The pop operation removes and returns the topmost element from the stack.
- Peek Operation: The peek operation returns the top element without removing it from the stack.
- isEmpty Operation: This operation checks whether the stack currently contains any elements.
Problem 1: Implement Stack Using Python List
Design a stack data structure that supports push, pop, peek, and isEmpty operations.
# Python program to implement stack
# operations- push, pop, peek, isEmpty
class Stack:
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop(self):
if self.is_empty():
return "Stack is empty"
return self.stack.pop()
def peek(self):
if self.is_empty():
return "Stack is empty"
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
# Driver code
s = Stack()
s.push(10)
s.push(20)
s.push(30)
print("Top element:", s.peek())
print("Removed:", s.pop())
print("Top after pop:", s.peek())
Output:
Explanation:Top element: 30
Removed: 30
Top after pop: 20
The append function adds elements to the end of the list, which represents the top of the stack. The pop function removes the last inserted element, which perfectly follows the LIFO principle.
What is a Queue? (Think Waiting Line)
A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means that the element inserted first is the first one to be removed.Key Operations
- Enqueue Operation: The enqueue operation inserts a new element at the rear of the queue.
- Dequeue Operation: The dequeue operation removes and returns the element from the front of the queue.
- Front Operation: The front operation returns the first element without removing it.
- isEmpty Operation: This operation checks whether the queue contains any elements.
Problem 2: Implement Queue Using List
Design a queue that supports enqueue, dequeue, front, and isEmpty operations.
# Python program to implement queue
# operations- enqueue, dequeue, front, isEmpty
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, val):
self.queue.append(val)
def dequeue(self):
if self.is_empty():
return "Queue is empty"
return self.queue.pop(0)
def front(self):
if self.is_empty():
return "Queue is empty"
return self.queue[0]
def is_empty(self):
return len(self.queue) == 0
# Driver code
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print("Front element:", q.front())
print("Removed:", q.dequeue())
print("Front after dequeue:", q.front())
Output:
Explanation:Front element: 10
Removed: 10
Front after dequeue: 20
The append function inserts elements at the rear of the queue. The pop(0) function removes the first element, ensuring that elements are processed in FIFO order.
Stack vs Queue
| Feature | Stack | Queue |
|---|---|---|
| Order of removal | A stack removes the most recently inserted element first. | A queue removes the earliest inserted element first. |
| Working principle | A stack follows the Last In, First Out principle. | A queue follows the First In, First Out principle. |
| Insertion point | In a stack, elements are always inserted at the top. | In a queue, elements are always inserted at the rear. |
| Deletion point | In a stack, elements are always removed from the top. | In a queue, elements are always removed from the front. |
| Real-life analogy | A stack behaves like a pile of plates where the last plate added is removed first. | A queue behaves like a line of people where the first person in line is served first. |
Problem 3: Valid Parentheses
Given a string containing parentheses, determine whether it is valid.
#Python program to check validity of
# parentheses
def is_valid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
else:
stack.append(char)
return len(stack) == 0
# Driver code
print(is_valid("()[]{}"))
print(is_valid("(]"))
Output:
Explanation:True
False
Each opening bracket is pushed onto the stack. When a closing bracket appears, the program checks whether it matches the top element. If it does not match, the string is invalid.
Problem 4: Implement Queue Using Two Stacks
Design a queue using two stacks only.
# Python program to implement queue
# two stacks
class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def enqueue(self, x):
self.s1.append(x)
def dequeue(self):
if not self.s2:
while self.s1:
self.s2.append(self.s1.pop())
return self.s2.pop()
# Driver code
q = MyQueue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
Output:
Explanation:1
2
The first stack stores elements as they come. When dequeue is required, elements are transferred to the second stack, which reverses their order and simulates FIFO behavior.
Where Are Stack and Queue Used?
Here are some practical applications of stacks and queues:Stack Use Cases
- Function Call Handling: A stack is used to manage function calls during program execution.
- Undo and Redo Operations: Applications use stacks to track changes and revert actions.
- Expression Evaluation: Stacks are used to evaluate mathematical expressions.
- Task Scheduling: Queues are used to manage tasks in operating systems.
- Breadth First Search: Queues are used in graph traversal algorithms.
- Real-Time Systems: Queues help in handling requests in order.
Time Complexity Summary
| Operation | Stack | Queue |
|---|---|---|
| Insertion | Stack insertion takes constant time. | Queue insertion takes constant time. |
| Deletion | Stack insertion takes constant time. | Queue insertion takes linear time due to shifting. |
Conclusion
Stacks and queues are not difficult once you understand their behavior clearly. A stack works best when you need to reverse the order of operations, while a queue works best when you need to maintain the order of processing. If you focus on visualizing how elements move and practice a few standard problems, these concepts become natural. That’s exactly what interviewers expect, not memorization, but clear understanding.Frequently Asked Questions
1. What is the main difference between stack and queue?2. Why is queue dequeue slower in Python list?A stack removes elements in reverse order of insertion, while a queue removes elements in the same order as insertion.
3. Can stack and queue be implemented without arrays?Because removing the first element shifts all remaining elements.
4. Which problems use stacks frequently?Yes, both can be implemented using linked lists.
5. Which problems use queues frequently?Problems involving parentheses, recursion, and backtracking use stacks.
Problems involving level order traversal and scheduling use queues.
0 Comments