Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find Longest Increasing Subsequence Length in Python
Compute the length of the longest increasing subsequence in an array using dynamic programming.
def longest_increasing_subsequence(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
if __name__ == "__main__":
# Demo with…
Find Maximum Distance Between Identical Elements in Python
Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.
from collections import defaultdict
def max_distance_between_identical(nums):
first_occurrence = {}
max_dist = 0
for i, num in enumerate(nums):
if num in first_occurrence:
dist = i - first_occurrence[num]
max_dist = max(max_dist, dist)
else:
first_occur…
Game of Life Next State Grid in Python
Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.
def next_state(grid):
m, n = len(grid), len(grid[0])
new = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
total = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
…
How to Compute Cosine Similarity Between Two Vectors in Python
This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.
import math
def cosine_similarity(vec_a, vec_b):
if len(vec_a) != len(vec_b):
raise ValueError("Vectors must have the same length")
dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
norm_a = math.sqrt(sum(a * a for a in vec_a))
norm_b = math.sqrt(sum(b * b for b in vec_b))
i…
How to Compute Jaccard Similarity in Python
Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.
def jaccard_similarity(list1, list2):
set1 = set(list1)
set2 = set(list2)
intersection = set1 & set2
union = set1 | set2
if not union:
return 0.0
return len(intersection) / len(union)
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
pri…
How to Compute the Cartesian Product of Two Lists in Python
Generates all ordered pairs from two lists using itertools.product and prints each combination.
from itertools import product
# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]
# Compute the Cartesian product
result = list(product(list_a, list_b))
# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
print(pair)
How to Compute the Dot Product of Two Lists in Python
Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.
def dot_product(list1, list2):
"""
Compute the dot product of two numeric lists.
The lists must have the same length.
"""
if len(list1) != len(list2):
raise ValueError("Lists must have the same length")
return sum(a * b for a, b in zip(list1, list2))
if __name__ == "__main__":
…
How to Implement a Moving Average from a Data Stream in Python
Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.
from collections import deque
class MovingAverage:
def __init__(self, size):
self.size = size
self.queue = deque()
self.window_sum = 0
def next(self, val):
self.queue.append(val)
self.window_sum += val
if len(self.queue) > self.size:
self.window_su…
How to Solve Daily Temperatures Days Until Warmer in Python
Compute the number of days until a warmer temperature for each day using a monotonic stack.
def daily_temperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i, temp in enumerate(temps):
while stack and temps[stack[-1]] < temp:
prev_idx = stack.pop()
result[prev_idx] = i - prev_idx
stack.append(i)
return result
if __name__ == …
How to Solve the Trapping Rain Water Problem in Python
Compute the total water trapped between elevation bars using a two-pointer O(n) algorithm.
def trap(height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
water = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
…
Product of Array Except Self in Python Without Division
Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.
from math import prod
def product_except_self(nums):
n = len(nums)
result = [1] * n
left_product = 1
for i in range(n):
result[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_product
right_product *…
Stable merge two lists by custom comparator in Python
Merge two lists into one sorted output using a custom comparator while maintaining the original order of equal elements.
from functools import cmp_to_key
def compare(x, y):
# Custom comparator: sorts by length first, then by original index for stability
if len(x) != len(y):
return len(x) - len(y)
return 0 # Equal keys preserve original order (stable)
def merge_stable(left, right, cmp_func):
result = []
i =…
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.