Reference library

Algorithms & data structures

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

36 matches
Algorithms & data structures medium

How to Solve Daily Temperatures Days Until Warmer in Python

Compute the number of days until a warmer temperature for each day using a monotonic stack.

stack monotonic algorithm
Python
def daily_temperatures(temps):
    n = len(temps)
    result = [0] * n
    stack = []
    
    for i, temp in enumerate(temps):
        while stack and temps[stack[-1]] < temp:
            prev_idx = stack.pop()
            result[prev_idx] = i - prev_idx
        stack.append(i)
    
    return result

if __name__ == …
12 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 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 medium

How to solve the stock span problem in Python

Calculate the stock span for each day's price using a monotonic stack in O(n) time.

stack monotonic-stack algorithm
Python
def stock_span(prices):
    span = [1] * len(prices)
    stack = []
    
    for i in range(len(prices)):
        while stack and prices[stack[-1]] <= prices[i]:
            stack.pop()
        span[i] = i - stack[-1] if stack else i + 1
        stack.append(i)
    
    return span

if __name__ == "__main__":
    pric…
13 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 medium

Merge k sorted lists in Python using a heap

Merge k individually sorted lists into one sorted list in Python using a min-heap.

heapq merge sorted-list
Python
import heapq

def merge_k_sorted_lists(lists):
    heap = []
    # Push the first element of each list onto the heap
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))
    
    result = []
    while heap:
        val, list_idx, elem_idx = heapq.heappop(heap)
        re…
15 0 Open
Algorithms & data structures medium

Product of All Elements Except Self in Python

Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.

array prefix suffix
Python
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 *= nums[i]
    
…
14 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 medium

Set Matrix Zeroes in Python: Markers List Grid Demo

Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.

matrix arrays algorithm
Python
def set_zeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    row_markers = [False] * rows
    col_markers = [False] * cols

    # First pass: record which rows and columns contain zeros
    for i in range(rows):
        for j in range(cols):
            if matrix[i][j] == 0:
                row_markers[i] …
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 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.