Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find the Equilibrium Index of a List in Python
Find every index in a list where the sum of elements to its left equals the sum to its right, using a single pass.
def find_equilibrium_indexes(arr):
total = sum(arr)
left_sum = 0
indexes = []
for i, num in enumerate(arr):
total -= num
if left_sum == total:
indexes.append(i)
left_sum += num
return indexes
if __name__ == "__main__":
test = [1, 2, 3, -1, 2, 3]
result =…
Generate Pascal's Triangle Rows in Python
Builds Pascal's triangle as a list of rows, where each inner value is the sum of the two values above it.
def generate_pascals_triangle(rows):
triangle = []
for row_num in range(rows):
row = [1] * (row_num + 1)
for col in range(1, row_num):
row[col] = triangle[row_num - 1][col - 1] + triangle[row_num - 1][col]
triangle.append(row)
return triangle
if __name__ == "__main__":
…
How to Build a Coordinate Grid with Nested Loops in Python
Generate a 2D list of (row, col) coordinate pairs using nested loops and return the grid structure.
def build_coordinate_grid(rows, cols):
"""Build a 2D grid of (row, col) coordinates using nested loops."""
grid = []
for r in range(rows):
row = []
for c in range(cols):
row.append((r, c))
grid.append(row)
return grid
if __name__ == "__main__":
grid = build_coo…
How to Combine filter and map with a List Comprehension in Python
This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.
def square(x):
return x * x
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = [square(x) for x in numbers if is_even(x)]
print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")
# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
How to Generate a Geometric Progression List in Python
This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.
def geometric_progression(first_term, ratio, count):
"""
Generate a list of 'count' terms in a geometric progression
starting with 'first_term' and multiplied by 'ratio' each step.
"""
progression = []
current = first_term
for _ in range(count):
progression.append(current)
c…
How to Map Strings to Uppercase in Python
Loops through a list of strings and builds a new list with each string converted to uppercase.
strings = ["hello", "world", "python", "skillset"]
uppercased = []
for s in strings:
uppercased.append(s.upper())
print(uppercased)
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 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…
Quickselect in Python: Find the kth Smallest Element
Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.
def quickselect(arr, k):
"""
Returns the k-th smallest element (0-indexed) using Quickselect.
Average: O(n), Worst: O(n^2)
"""
if len(arr) == 1:
return arr[0]
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
if k < len(l…
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.