Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Bucket Numbers into Histogram Bin Counts in Python
Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.
from collections import Counter
def histogram_bins(numbers, num_bins):
"""Bucket numbers into histogram bin counts."""
if not numbers:
return []
min_val = min(numbers)
max_val = max(numbers)
bin_width = (max_val - min_val) / num_bins
# Handle edge case where all values are id…
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
Depth First Search Traversal Order in Python
Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.
def dfs_order(adj, start):
visited = set()
order = []
def dfs(node):
visited.add(node)
order.append(node)
for neighbor in adj.get(node, []):
if neighbor not in visited:
dfs(neighbor)
dfs(start)
return order
if __name__ == "__main__":
# Dem…
Extract n largest elements from a large list using heapq
Uses heapq.nlargest to efficiently extract the top n largest numbers from a large list, even with millions of elements.
import heapq
import random
def n_largest(numbers, n):
"""Return the n largest numbers from a list using heapq."""
if n <= 0:
return []
return heapq.nlargest(n, numbers)
if __name__ == "__main__":
# Create a large list with 1,000,000 random numbers
large_list = [random.randint(1, 1_000_000…
Filter List to Keep Only Whitelist Values in Python
Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.
def filter_whitelist(values, whitelist):
"""Return only values that are present in the whitelist set."""
return [value for value in values if value in whitelist]
if __name__ == "__main__":
raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
allowed = {"apple", "banana", "date"}
…
Find All Indices of a Target Value in a Python List
Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.
def find_all_indices(arr, target):
return [i for i, value in enumerate(arr) if value == target]
if __name__ == "__main__":
sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
target = 2
result = find_all_indices(sample_list, target)
print(result)
Find Common Elements in List of Lists in Python
Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.
from collections import Counter
def common_elements(list_of_lists):
"""Return elements present in every sublist."""
if not list_of_lists:
return []
counts = Counter(list_of_lists[0])
for sublist in list_of_lists[1:]:
counts &= Counter(sublist)
return list(counts.elements())
if _…
Find Elements in One Python List but Not Another
Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.
def difference_elements(a, b):
"""Return elements present in list a but not in list b."""
set_b = set(b)
return [item for item in a if item not in set_b]
if __name__ == "__main__":
a = [1, 2, 3, 4, 5, 3, 2]
b = [2, 4, 6]
result = difference_elements(a, b)
print(f"A: {a}")
print(f"B: {b…
Find First Duplicate Index in Python
Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.
def find_first_duplicate(arr):
seen = {}
for index, value in enumerate(arr):
if value in seen:
return index
seen[value] = index
return -1
if __name__ == "__main__":
test_array = [3, 5, 2, 8, 5, 1, 2]
result = find_first_duplicate(test_array)
print(f"Array: {test_arr…
Find Longest Consecutive Run in an Unsorted List in Python
Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.
def longest_run(nums):
if not nums:
return 0
num_set = set(nums)
longest = 0
for num in num_set:
# Only start counting from the smallest number in a sequence
if num - 1 not in num_set:
current = num
length = 1
while current + 1 in num_set:
…
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…
Find Missing Number in Python Sequence 1 to N
Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.
def find_missing_number(nums, n):
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
if __name__ == "__main__":
n = 10
numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
missing = find_missing_number(numbers, n)
print(f"The missing number is: {missing}")
Find Single Number Appearing Once in Python
Count frequency of each number in a list and return the one that appears exactly once when all others appear twice.
from collections import Counter
def find_single_number(nums):
counts = Counter(nums)
for num, count in counts.items():
if count == 1:
return num
return None
if __name__ == "__main__":
nums = [4, 1, 2, 1, 2]
result = find_single_number(nums)
print(f"Single number in {nums} …
Find k Closest Points to Origin in Python
Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.
import math
def k_closest(points, k):
points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
return points[:k]
if __name__ == "__main__":
points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
k = 3
result = k_closest(points, k)
print(f"Original points: {points}")
print(f"K closest points (k…
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 =…
Find the Last Index Where a Condition Is True in Python
This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.
def last_index_where(sequence, condition):
"""Return the index of the last element in sequence that satisfies condition."""
for i in range(len(sequence) - 1, -1, -1):
if condition(sequence[i]):
return i
return -1
if __name__ == "__main__":
numbers = [1, 4, 7, 2, 9, 5, 8, 3]
is_…
Find the Second Largest Unique Number in a Python List
This Python function finds the second largest unique number from a list by converting it to a set, removing the maximum, and returning the new maximum.
def second_largest_unique(numbers):
unique_numbers = set(numbers)
if len(unique_numbers) < 2:
return None
unique_numbers.remove(max(unique_numbers))
return max(unique_numbers)
if __name__ == "__main__":
test_list = [4, 2, 9, 5, 2, 9, 1, 5]
result = second_largest_unique(test_list)
…
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 Add Two Lists Elementwise in Python
Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.
def elementwise_add(list1, list2):
return [a + b for a, b in zip(list1, list2)]
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [10, 20, 30, 40]
result = elementwise_add(list_a, list_b)
print(result)
How to Apply a Function to Sliding Window Slices in Python
This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.
def apply_to_sliding_windows(data, window_size, func):
return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 6]
window_size = 3
results = apply_to_sliding_windows(numbers, window_size, sum)
print(results)
results…
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 Compare Two Lists Elementwise for Greater Flags in Python
Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.
def compare_lists_greater(list_a, list_b):
"""
Compare two lists elementwise and return a list of booleans
indicating whether each element in list_a is greater than the
corresponding element in list_b.
"""
if len(list_a) != len(list_b):
raise ValueError("Lists must have the same length"…
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…
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.