Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Implement Insert Delete GetRandom O(1) in Python
Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.
import random
class RandomizedSet:
def __init__(self):
self.values = []
self.index_map = {}
def insert(self, val):
if val in self.index_map:
return False
self.index_map[val] = len(self.values)
self.values.append(val)
return True
def delete(self…
Implement Queue Using Two Stacks in Python
Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.
class QueueUsingStacks:
def __init__(self):
self.stack_in = []
self.stack_out = []
def enqueue(self, value):
self.stack_in.append(value)
def dequeue(self):
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
…
Implement a Stack Using List Push Pop in Python
A minimal Stack class built on a Python list, with push, pop, peek, is_empty, and size methods, including empty-stack guards.
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…
Browse by section
Each section groups closely related Python snippets.
Algorithms & data structures — Python code examples
What you will find here
This page collects algorithms & data structures snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.