Reference library

Algorithms & data structures

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

36 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

Binary Search on Answer in Python: Koko Eating Bananas

Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.

binary-search algorithms search
Python
import math

def min_eating_speed(piles, h):
    """Return minimum integer eating speed K so Koko finishes within h hours."""
    def hours_needed(speed):
        return sum(math.ceil(p / speed) for p in piles)

    low, high = 1, max(piles)
    while low < high:
        mid = (low + high) // 2
        if hours_needed…
15 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)
        …
16 0 Open
Algorithms & data structures medium

Find All Triplets with Sum Zero in Python

This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.

triplets two-pointers sorting
Python
def find_triplets(nums):
    nums.sort()
    n = len(nums)
    triplets = []
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
    …
14 0 Open
Algorithms & data structures medium

Find Longest Consecutive Sequence in Python

Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.

set longest-sequence hash-table
Python
def longest_consecutive_length(nums):
    num_set = set(nums)
    longest = 0
    
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            current_streak = 1
            
            while current + 1 in num_set:
                current += 1
                current_streak += 1
…
13 0 Open
Algorithms & data structures medium

Find Longest Increasing Subsequence Length in Python

Compute the length of the longest increasing subsequence in an array using dynamic programming.

dynamic-programming subsequence algorithm
Python
def longest_increasing_subsequence(nums):
    if not nums:
        return 0
    
    dp = [1] * len(nums)
    
    for i in range(1, len(nums)):
        for j in range(i):
            if nums[i] > nums[j]:
                dp[i] = max(dp[i], dp[j] + 1)
    
    return max(dp)

if __name__ == "__main__":
    # Demo with…
15 0 Open
Algorithms & data structures medium

Find Minimum in Rotated Sorted List in Python

Uses binary search to find the minimum element in a rotated sorted list in O(log n) time.

binary-search minimum rotated-array
Python
def find_min(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[right]:
            left = mid + 1
        else:
            right = mid
    return nums[left]


if __name__ == "__main__":
    rotated = [4, 5, 6, 7, 0, 1, 2]
    print(f"Minimu…
12 0 Open
Algorithms & data structures medium

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.

algorithms sets counting
Python
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…
12 0 Open
Algorithms & data structures medium

Find Peak Element in Python Using Binary Search

A binary search solution that finds any peak element (an element strictly greater than its neighbors) in an unsorted array in O(log n) time.

binary-search peak array
Python
def find_peak_element(nums):
    left, right = 0, len(nums) - 1
    
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[mid + 1]:
            right = mid
        else:
            left = mid + 1
            
    return left

if __name__ == "__main__":
    test1 = [1, 2, 3, 1]
    tes…
17 0 Open
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Algorithms & data structures medium

Find the Majority Element in Python with Boyer-Moore Vote

Use Boyer-Moore majority vote to find the element appearing more than n/2 times in an array in O(n) time and O(1) space.

boyer-moore majority-element array
Python
def majority_element(nums):
    candidate = None
    count = 0

    for num in nums:
        if count == 0:
            candidate = num
        count += 1 if num == candidate else -1

    return candidate

if __name__ == "__main__":
    nums = [2, 2, 1, 1, 1, 2, 2]
    result = majority_element(nums)
    print(f"Major…
14 0 Open
Algorithms & data structures medium

Find two unique numbers in an array with Python

Returns the two numbers that appear exactly once in a list where every other number appears twice, using XOR bit manipulation.

bit-manipulation xor arrays
Python
def find_two_odd(arr):
    """Return the two numbers that appear exactly once, while all others appear twice."""
    xor_all = 0
    for num in arr:
        xor_all ^= num

    # xor_all now equals the XOR of the two unique numbers.
    # Find a set bit (any bit where they differ).
    diff_bit = xor_all & (-xor_all)
…
13 0 Open
Algorithms & data structures medium

Game of Life Next State Grid in Python

Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.

game-of-life grid cellular-automaton
Python
def next_state(grid):
    m, n = len(grid), len(grid[0])
    new = [[0] * n for _ in range(m)]
    for r in range(m):
        for c in range(n):
            total = 0
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    if dr == 0 and dc == 0:
                        continue
   …
14 0 Open
Algorithms & data structures medium

How to Decode a String with Repeated Brackets in Python

Decodes strings with patterns like '3[a]2[bc]' by using a stack to handle nested and repeated bracket groups.

stack string-decoding algorithms
Python
def decode_string(s: str) -> str:
    stack = []
    current_num = 0
    current_str = ""

    for ch in s:
        if ch.isdigit():
            current_num = current_num * 10 + int(ch)
        elif ch == "[":
            stack.append((current_str, current_num))
            current_str = ""
            current_num = 0…
13 0 Open
Algorithms & data structures medium

How to Detect Hardcoded Secrets in Python Source Code

A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.

secrets regex security
Python
import re

def detect_secrets(text):
    """Detect potential hardcoded secrets in source code."""
    patterns = {
        'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
        'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
        'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
43 0 Open
Algorithms & data structures medium

How to Evaluate RPN Expressions in Python

Use a stack to evaluate Reverse Polish Notation token lists with a dictionary of operator lambdas, truncating division toward zero.

rpn stack expression
Python
def eval_rpn(tokens):
    stack = []
    ops = {
        '+': lambda a, b: a + b,
        '-': lambda a, b: a - b,
        '*': lambda a, b: a * b,
        '/': lambda a, b: int(a / b)  # truncate toward zero
    }
    for token in tokens:
        if token in ops:
            b = stack.pop()
            a = stack.pop(…
12 0 Open
Algorithms & data structures medium

How to Find Four Sum Quadruplets in Python (Sorted Demo)

Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.

two-pointers sorting four-sum
Python
def four_sum(nums, target):
    nums.sort()
    result = []
    n = len(nums)

    for i in range(n - 3):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        for j in range(i + 1, n - 2):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue
            left, right = j + 1…
13 0 Open
Algorithms & data structures medium

How to Find Intersection of Two Sorted Interval Lists in Python

A two-pointer algorithm that finds all overlapping intervals between two sorted lists of intervals.

intervals two-pointers algorithm
Python
def interval_intersection(list1, list2):
    i = j = 0
    result = []
    
    while i < len(list1) and j < len(list2):
        # Find the overlap between current intervals
        lo = max(list1[i][0], list2[j][0])
        hi = min(list1[i][1], list2[j][1])
        
        # If there's an overlap, add it to result
…
13 0 Open
Algorithms & data structures medium

How to Find Minimum Swaps to Sort an Array in Python

Calculate the minimum number of adjacent-free swaps needed to sort a permutation array using cycle detection in Python.

sorting cycles greedy
Python
def min_swaps_to_sort(arr):
    n = len(arr)
    arr_pos = sorted((val, idx) for idx, val in enumerate(arr))
    visited = [False] * n
    swaps = 0

    for i in range(n):
        if visited[i] or arr_pos[i][1] == i:
            continue

        cycle_size = 0
        j = i
        while not visited[j]:
            …
13 0 Open
Algorithms & data structures medium

How to Find the Next Greater Element for Each List Item in Python

Use a monotonic stack to find the next greater element to the right for every item in a list, in O(n) time.

stack monotonic stack algorithm
Python
def next_greater_element(nums):
    result = [-1] * len(nums)
    stack = []
    
    for i in range(len(nums) - 1, -1, -1):
        while stack and stack[-1] <= nums[i]:
            stack.pop()
        result[i] = stack[-1] if stack else -1
        stack.append(nums[i])
    
    return result


if __name__ == "__main…
13 0 Open
Algorithms & data structures medium

How to Find the Previous Smaller Element in Python

Use a monotonic stack to find the nearest smaller element to the left of each item in a list, returning -1 when none exists.

monotonic stack stack arrays
Python
from collections import deque

def previous_smaller_elements(arr):
    stack = deque()
    result = [-1] * len(arr)

    for i in range(len(arr)):
        while stack and arr[stack[-1]] >= arr[i]:
            stack.pop()
        if stack:
            result[i] = arr[stack[-1]]
        stack.append(i)

    return resul…
15 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 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 medium

How to Search a Rotated Sorted List in Python

Binary search a pivot-rotated sorted list for a target value and return its index in O(log n) time.

binary-search rotated-array search-algorithm
Python
from typing import List

def search_rotated(nums: List[int], target: int) -> int:
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid

        # left half is sorted
        if nums[left] <= nums[mid]:
            if nums[…
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.