I've been teaching stack and queue data structures with python examples for years, and the #1 question I get is: "How does this actually work in practice?" This guide answers that question with real examples.
Table of Contents
Understanding Stack and Queue Data Structures with Python Examples
Data structures and algorithms are the foundation of computer science. Let's explore stack and queue data structures with python examples with clear implementations.
# Stack and Queue Data Structures with Python Examples — Python implementation
def binary_search(arr, target):
"""
Binary search in a sorted array.
Time: O(log n) | Space: O(1)
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not found
# Test
sorted_array = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(f"Found 23 at index: {binary_search(sorted_array, 23)}") # 5
print(f"Found 99 at index: {binary_search(sorted_array, 99)}") # -1
Implementation Details
# Stack implementation
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek at empty stack")
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
# Practical use: balanced parentheses checker
def is_balanced(expression):
stack = Stack()
pairs = {')': '(', ']': '[', '}': '{'}
for char in expression:
if char in '([{':
stack.push(char)
elif char in ')]}':
if stack.is_empty() or stack.pop() != pairs[char]:
return False
return stack.is_empty()
print(is_balanced("({[()]})")) # True
print(is_balanced("({[()]}")) # False
print(is_balanced(")(")) # False
Time and Space Complexity
| Algorithm | Best | Average | Worst | Space |
|---|---|---|---|---|
| Binary Search | O(1) | O(log n) | O(log n) | O(1) |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| BFS/DFS | O(V+E) | O(V+E) | O(V+E) | O(V) |
Practice Problems
Try these coding challenges to practice:
# Problem: Find two numbers that sum to target
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1] (2 + 7 = 9)
# Problem: Reverse a linked list
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
AM
Arjun Mehta
Full-Stack Developer & Technical Writer at DRIXO
Full-Stack Developer & Technical Writer at DRIXO
Full-stack developer with 5+ years of experience in Python and JavaScript. I love breaking down complex concepts into simple, practical tutorials. When I'm not coding, you'll find me contributing to open-source projects.
Comments