Reference library

Algorithms & data structures

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

13 matches
Algorithms & data structures medium

Binary Search for Ship Capacity in Python

Use binary search to find the minimum ship capacity that can transport all packages within a given number of days.

binary search greedy capacity
Python
def ship_within_days(weights, days):
    def can_ship(capacity):
        current = 0
        needed_days = 1
        for weight in weights:
            if current + weight > capacity:
                needed_days += 1
                current = 0
            current += weight
        return needed_days <= days

    low …
13 0 Open
Algorithms & data structures medium

Container With Most Water: Two-Pointer Solution in Python

Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.

two-pointer array algorithm
Python
from typing import List

def max_water_container(heights: List[int]) -> int:
    left, right = 0, len(heights) - 1
    max_area = 0
    
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        area = width * height
        max_area = max(max_area, area)
        …
15 0 Open
Algorithms & data structures easy

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.

heapq heaps large-data
Python
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…
14 0 Open
Algorithms & data structures easy

How to Apply a Function to Sliding Window Slices in Python

This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.

sliding-window list-comprehension algorithms
Python
def apply_to_sliding_windows(data, window_size, func):
    return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 6]
    window_size = 3
    results = apply_to_sliding_windows(numbers, window_size, sum)
    print(results)
    results…
16 0 Open
Algorithms & data structures medium

How to Find the n Smallest Items in a Large List with heapq in Python

This code demonstrates how to efficiently extract the n smallest items from a large list using Python's heapq module and a manual max-heap approach.

heapq heaps large data
Python
import heapq

def n_smallest_iterable(data, n):
    """Return the n smallest items without loading the whole list."""
    if n <= 0:
        return []
    return heapq.nsmallest(n, data)

def n_smallest_manual(data, n):
    """Return the n smallest using a heap, O(n log k) time."""
    if n <= 0:
        return []
   …
13 0 Open
Algorithms & data structures easy

How to Generate Fibonacci Sequence in Python

Generate the first n Fibonacci numbers as a list using a simple iterative loop.

fibonacci sequences iteration
Python
def fibonacci(n):
    """Generate the first n terms of the Fibonacci sequence."""
    if n <= 0:
        return []
    seq = [0, 1]
    while len(seq) < n:
        seq.append(seq[-1] + seq[-2])
    return seq[:n]

if __name__ == "__main__":
    n = 10
    result = fibonacci(n)
    print(result)
13 0 Open
Algorithms & data structures medium

How to Generate a Power Set in Python with Bitmasks

Generate the power set of a small list using a bitmask approach, producing all possible subsets.

bitmask power set subset generation
Python
def power_set(items):
    """Generate the power set of a list using bitmask approach."""
    n = len(items)
    result = []
    
    for mask in range(1 << n):
        subset = []
        for i in range(n):
            if mask & (1 << i):
                subset.append(items[i])
        result.append(subset)
    
    r…
14 0 Open
Algorithms & data structures easy

How to Get the Breadth-First Traversal Order of a Graph in Python

Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.

graph bfs queue
Python
from collections import deque

def bfs_order(adjacency, start=0):
    """Return the order nodes are visited in a breadth-first traversal."""
    visited = set()
    order = []
    queue = deque([start])
    visited.add(start)

    while queue:
        node = queue.popleft()
        order.append(node)

        for neig…
14 0 Open
Algorithms & data structures easy

How to Rotate an Array by k Steps in Python

This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.

array rotation algorithms
Python
def rotate_array(nums, k):
    if not nums:
        return []
    n = len(nums)
    k = k % n
    return nums[-k:] + nums[:-k] if k else nums[:]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 2
    result = rotate_array(arr, k)
    print(f"Original: {arr}")
    print(f"Rotated by {k}: {result}")
13 0 Open
Algorithms & data structures easy

How to partition a list into n nearly equal parts in Python

Divide a list into n contiguous chunks of nearly equal size using an average-length calculation that distributes the remainder evenly.

partitioning chunks slicing
Python
def partition(lst, n):
    """Partition a list into n nearly equal contiguous parts."""
    if n <= 0:
        raise ValueError("n must be positive")
    if not lst:
        return [[] for _ in range(n)]
    
    parts = []
    avg = len(lst) / n
    last_idx = 0.0
    
    while last_idx < len(lst):
        end_idx =…
14 0 Open
Algorithms & data structures easy

Remove item at index without pop in Python

Remove an item at a given index from a list without using pop by slicing the list around the index.

list slicing algorithms
Python
def remove_at_index(lst, index):
    """Remove item at index and return the new list."""
    if index < 0 or index >= len(lst):
        raise IndexError("Index out of range")
    return lst[:index] + lst[index + 1:]


if __name__ == "__main__":
    items = [10, 20, 30, 40, 50]
    result = remove_at_index(items, 2)
  …
12 0 Open
Algorithms & data structures easy

Reorder a List by Odd Even Indices in Python

Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.

list indices reorder
Python
def reorder_by_odd_even(items):
    """Reorders a list so that elements at odd indices come first,
    followed by elements at even indices (1-based).
    
    Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
    """
    odds = [items[i] for i in range(1, len(items), 2)]
    evens = [items[i] for i in range(0, len(items), …
18 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

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.