Reference library

Algorithms & data structures

Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.

14 matches
Algorithms & data structures easy

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.

set consecutive linear-scan
Python
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:
 …
11 0 Open
Algorithms & data structures easy

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.

median two-pointer merge
Python
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.…
16 0 Open
Algorithms & data structures easy

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.

sorting euclidean-distance geometry
Python
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…
13 0 Open
Algorithms & data structures easy

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.

intervals pairwise sorting
Python
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), (…
14 0 Open
Algorithms & data structures easy

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.

bisect binary-search sorted-list
Python
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…
15 0 Open
Algorithms & data structures easy

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.

array sorting partition
Python
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…
13 0 Open
Algorithms & data structures easy

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'.

ranges compression arrays
Python
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:
         …
15 0 Open
Algorithms & data structures easy

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.

bisect sorted-list insertion
Python
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}"…
14 0 Open
Algorithms & data structures easy

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.

merge in-place arrays
Python
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__":
 …
15 0 Open
Algorithms & data structures easy

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.

two-pointers array sorting
Python
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…
14 0 Open
Algorithms & data structures easy

Sort Unique Values by Frequency in Python

Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.

counter sorting frequency
Python
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…
12 0 Open
Algorithms & data structures easy

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.

sorting tuples lambda
Python
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__"…
14 0 Open
Algorithms & data structures easy

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.

merge stable-sort custom-comparator
Python
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 =…
13 0 Open
Algorithms & data structures easy

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.

sorting stable sort timsort
Python
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))
 …
13 0 Open

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.