Reference library

Algorithms & data structures

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

65 matches
Algorithms & data structures easy

How to Sample Random Items Without Replacement in Python

Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.

random sampling algorithms
Python
import random

def sample_without_replacement(population, k):
    """Return k random items from population without replacement."""
    if k > len(population):
        raise ValueError("k cannot exceed population size")
    # Use random.sample for O(k) time, no mutation of the original
    return random.sample(populati…
15 0 Open
Algorithms & data structures medium

How to Solve the Trapping Rain Water Problem in Python

Compute the total water trapped between elevation bars using a two-pointer O(n) algorithm.

algorithms two-pointers arrays
Python
def trap(height):
    if not height:
        return 0
    
    left, right = 0, len(height) - 1
    left_max, right_max = 0, 0
    water = 0
    
    while left < right:
        if height[left] < height[right]:
            if height[left] >= left_max:
                left_max = height[left]
            else:
         …
17 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 medium

How to Sort Colors (Dutch National Flag) in Python

In-place sorting of a list of 0s, 1s, and 2s using the Dutch National Flag algorithm with O(n) time and O(1) space.

algorithm sorting two-pointers
Python
def sort_colors(nums):
    low, mid, high = 0, 0, len(nums) - 1

    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:  # nums[mid] == 2
            nums[mid], n…
14 0 Open
Algorithms & data structures easy

How to Split a List by a Predicate into Two Lists in Python

Partition any Python list into two lists based on a predicate: items that match go into one list, everything else into the other.

list predicate partition
Python
from typing import Callable, List, TypeVar

T = TypeVar("T")

def split_by_predicate(items: List[T], predicate: Callable[[T], bool]) -> tuple[List[T], List[T]]:
    matching = []
    non_matching = []
    for item in items:
        if predicate(item):
            matching.append(item)
        else:
            non_mat…
11 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

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 medium

Implement Insert Delete GetRandom O(1) in Python

Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.

randomized-set o1-lookup hash-map
Python
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_map = {}

    def insert(self, val):
        if val in self.index_map:
            return False
        self.index_map[val] = len(self.values)
        self.values.append(val)
        return True

    def delete(self…
12 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

Insert an Element Every n Positions in Python

Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.

list-manipulation insertion algorithms
Python
def insert_every_n(seq, element, n, position="after"):
    """Insert an element before or after every n-th position in a list.

    Args:
        seq: Input list
        element: Element to insert
        n: Insert every n positions (n > 0)
        position: 'before' or 'after' (default: 'after')
    Returns:
        …
13 0 Open
Algorithms & data structures medium

Product of Array Except Self in Python Without Division

Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.

arrays prefix-product suffix-product
Python
from math import prod


def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]

    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *…
14 0 Open
Algorithms & data structures medium

Quickselect in Python: Find the kth Smallest Element

Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.

quickselect selection algorithm
Python
def quickselect(arr, k):
    """
    Returns the k-th smallest element (0-indexed) using Quickselect.
    Average: O(n), Worst: O(n^2)
    """
    if len(arr) == 1:
        return arr[0]

    pivot = arr[-1]
    left = [x for x in arr[:-1] if x <= pivot]
    right = [x for x in arr[:-1] if x > pivot]

    if k < len(l…
16 0 Open
Algorithms & data structures easy

Segregate Negative Numbers Before Positives in Python

Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.

lists partition stability
Python
def segregate_negatives(numbers):
    """Segregate negatives before positives without altering relative order."""
    negatives = [n for n in numbers if n < 0]
    positives = [n for n in numbers if n >= 0]
    return negatives + positives


if __name__ == "__main__":
    sample = [3, -1, 4, -5, 2, -9, 0]
    result =…
14 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 medium

Split Array Largest Sum in Python (Minimize Largest Subarray Sum)

Binary search + greedy check to split an array into k subarrays while minimizing the largest subarray sum.

binary-search greedy array
Python
def can_split(nums, k, max_sum):
    subarrays = 1
    current_sum = 0
    for num in nums:
        if current_sum + num <= max_sum:
            current_sum += num
        else:
            subarrays += 1
            current_sum = num
            if subarrays > k:
                return False
    return True

def spli…
15 0 Open
Algorithms & data structures easy

Take While Predicate True From Start in Python

Create a custom take_while function that collects elements from an iterable until a predicate returns False, then stops.

takewhile iteration predicate
Python
def take_while(predicate, iterable):
    """Return elements from iterable until the predicate becomes False."""
    result = []
    for item in iterable:
        if predicate(item):
            result.append(item)
        else:
            break
    return result


if __name__ == "__main__":
    numbers = [2, 4, 6, 7,…
13 0 Open
Algorithms & data structures medium

Validate Sudoku Board Rows Columns and Boxes in Python

Validate a 9x9 Sudoku board by checking that each row, column, and 3x3 box contains the numbers 1 through 9 exactly once.

sudoku validation matrix
Python
def validate_sudoku(board):
    def is_valid_group(group):
        return sorted(group) == list(range(1, 10))

    def get_columns():
        return [[board[r][c] for r in range(9)] for c in range(9)]

    def get_boxes():
        boxes = []
        for box_row in range(0, 9, 3):
            for box_col in range(0, 9,…
11 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.