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…
Drop Elements From Start While Condition Is True in Python
This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.
def drop_while(predicate, iterable):
"""Drop elements from the start while predicate is true."""
it = iter(iterable)
for item in it:
if not predicate(item):
yield item
break
yield from it
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 1, 2, 5]
result = list(d…
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 Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
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 Median of Two Sorted Arrays in Python
Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.
def median_of_two_sorted_arrays(nums1, nums2):
merged = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.…
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 Pivot Index in Python
Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.
def find_pivot_index(nums):
total = sum(nums)
left_sum = 0
for i, num in enumerate(nums):
if left_sum == total - left_sum - num:
return i
left_sum += num
return -1
if __name__ == "__main__":
test_cases = [
[1, 7, 3, 6, 5, 6],
[1, 2, 3],
[2, 1, -…
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 First Index Where a Condition Is True in Python
Search any iterable for the first element matching a predicate and return its index, or -1 if none match.
def first_true_index(items, condition):
"""Return the first index where condition(item) is True, or -1 if none match."""
for i, item in enumerate(items):
if condition(item):
return i
return -1
if __name__ == "__main__":
numbers = [1, 3, 5, 8, 10, 12]
# Find first number greate…
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)
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.