Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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…
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 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:
…
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…
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.