Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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 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 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…
How to Find Gaps Between Sorted Intervals in Python
This code finds gap ranges between sorted intervals using pairwise iteration, returning ranges where no interval covers.
from itertools import pairwise
def find_gaps(intervals):
intervals = sorted(intervals)
gaps = []
for prev, curr in pairwise(intervals):
if prev[1] < curr[0]:
gaps.append((prev[1] + 1, curr[0] - 1))
return gaps
if __name__ == "__main__":
intervals = [(1, 3), (5, 7), (10, 12), (…
How to Find the Nearest Value to a Target in a Sorted List in Python
Use bisect to binary-search a sorted list and return the element closest to a target value.
import bisect
def nearest_value(sorted_list, target):
if not sorted_list:
return None
pos = bisect.bisect_left(sorted_list, target)
if pos == 0:
return sorted_list[0]
if pos == len(sorted_list):
return sorted_list[-1]
before = sorted_list[pos - 1]
after = sorted_list[po…
How to Sort Array by Parity (Even Before Odd) in Python
Rearrange an array so all even numbers appear before all odd numbers using a simple two-list partition approach.
def sort_array_by_parity(nums):
"""
Rearrange the array so that all even integers come first,
followed by all odd integers. The order within even and odd
groups is not required to be sorted.
"""
even = []
odd = []
for num in nums:
if num % 2 == 0:
even.append(nu…
How to compress consecutive numbers into range strings in Python
Convert a sorted list of consecutive integers into compact range strings like '1-3', '5-6', and '15'.
def compress_ranges(nums):
"""Convert a list of sorted consecutive numbers into range strings."""
if not nums:
return []
ranges = []
start = prev = nums[0]
for num in nums[1:]:
if num == prev + 1:
prev = num
else:
if start == prev:
…
Insert Multiple Values Into a Sorted List in Python
Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.
import bisect
def insert_sorted(sorted_list, values):
for value in values:
bisect.insort(sorted_list, value)
return sorted_list
if __name__ == "__main__":
original = [1, 3, 5, 7, 9]
new_values = [4, 6, 2, 8, 0]
result = insert_sorted(original, new_values)
print(f"Original: {original}"…
Merge Two Sorted Arrays Without Extra Space in Python
Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.
def merge_sorted(arr1, arr2):
m, n = len(arr1), len(arr2)
i, j = m - 1, n - 1
while j >= 0:
if i >= 0 and arr1[i] > arr2[j]:
arr1[i + j + 1] = arr1[i]
i -= 1
else:
arr1[i + j + 1] = arr2[j]
j -= 1
return arr1
if __name__ == "__main__":
…
Rearrange array alternately max min in Python
Rearranges a sorted list so its elements alternate between the current maximum and current minimum using two pointers in O(n) time.
def rearrange_alternately(arr):
"""
Rearrange sorted array so elements alternate: max, min, next max, next min...
Returns a new list in O(n) time using O(n) space.
"""
n = len(arr)
result = []
left, right = 0, n - 1
while left <= right:
if left == right:
result.appen…
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…
Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
def sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__"…
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 =…
Stable sort preserving equal order demo in Python
Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.
from operator import itemgetter
def stable_sort_demo():
data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
print("Original:", data)
# Sort by first element (the tuple's first value), keeping relative order of equal items
sorted_data = sorted(data, key=itemgetter(0))
…
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.