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]:
…
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 Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
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} …
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 Count Distinct Elements in a List in Python
Count the number of unique items in a list by converting it to a set and returning its length.
def count_distinct_elements(items):
return len(set(items))
if __name__ == "__main__":
sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
result = count_distinct_elements(sample)
print(result)
How to Count Occurrences of Each Value in Python
Count how many times each value appears in a list using Python's Counter from the collections module.
from collections import Counter
def count_occurrences(values):
"""Return a dictionary mapping each value to its count."""
return dict(Counter(values))
if __name__ == "__main__":
sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
result = count_occurrences(sample_data)
print(r…
How to Implement a Recent Counter with a Deque in Python
Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.
from collections import deque
import time
class RecentCounter:
def __init__(self):
self.hits = deque()
def ping(self, t: int) -> int:
self.hits.append(t)
while self.hits and self.hits[0] < t - 3000:
self.hits.popleft()
return len(self.hits)
if __name__ == "__mai…
Sort Unique Values by Frequency in Python
Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.
from collections import Counter
def sort_unique_by_frequency(values):
counts = Counter(values)
return sorted(counts.keys(), key=lambda x: (-counts[x], x))
if __name__ == "__main__":
data = [4, 2, 2, 8, 3, 3, 1, 3, 5, 5, 5, 5, 1]
result = sort_unique_by_frequency(data)
print(f"Sorted unique values…
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.