Reference library

Algorithms & data structures

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

63 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)
        …
15 0 Open
Algorithms & data structures easy

Drop Elements From Start While Condition Is True in Python

This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.

generator iteration filtering
Python
def drop_while(predicate, iterable):
    """Drop elements from the start while predicate is true."""
    it = iter(iterable)
    for item in it:
        if not predicate(item):
            yield item
            break
    yield from it

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 1, 2, 5]
    result = list(d…
12 0 Open
Algorithms & data structures easy

Find Elements Appearing More Than n/3 Times in Python

Return all elements that occur more than len(array)/3 times using a simple dictionary counter.

majority-element dictionary counting
Python
def majority_third(arr):
    """Return elements appearing more than len(arr)/3 times."""
    cutoff = len(arr) / 3
    counts = {}
    for x in arr:
        counts[x] = counts.get(x, 0) + 1
    return [x for x, c in counts.items() if c > cutoff]


if __name__ == "__main__":
    test1 = [3, 2, 3]
    test2 = [1, 1, 1, …
11 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 easy

Find Maximum Distance Between Identical Elements in Python

Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.

arrays hashmap algorithms
Python
from collections import defaultdict

def max_distance_between_identical(nums):
    first_occurrence = {}
    max_dist = 0

    for i, num in enumerate(nums):
        if num in first_occurrence:
            dist = i - first_occurrence[num]
            max_dist = max(max_dist, dist)
        else:
            first_occur…
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.…
15 0 Open
Algorithms & data structures easy

Find Missing Number in Python Sequence 1 to N

Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.

missing-number arithmetic sum
Python
def find_missing_number(nums, n):
    expected_sum = n * (n + 1) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum


if __name__ == "__main__":
    n = 10
    numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
    missing = find_missing_number(numbers, n)
    print(f"The missing number is: {missing}")
15 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 easy

Find Pivot Index in Python

Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.

pivot array prefix-sum
Python
def find_pivot_index(nums):
    total = sum(nums)
    left_sum = 0
    for i, num in enumerate(nums):
        if left_sum == total - left_sum - num:
            return i
        left_sum += num
    return -1


if __name__ == "__main__":
    test_cases = [
        [1, 7, 3, 6, 5, 6],
        [1, 2, 3],
        [2, 1, -…
13 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…
12 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 easy

Find the Last Index Where a Condition Is True in Python

This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.

search list reverse
Python
def last_index_where(sequence, condition):
    """Return the index of the last element in sequence that satisfies condition."""
    for i in range(len(sequence) - 1, -1, -1):
        if condition(sequence[i]):
            return i
    return -1

if __name__ == "__main__":
    numbers = [1, 4, 7, 2, 9, 5, 8, 3]
    is_…
12 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 easy

Find the Second Largest Unique Number in a Python List

This Python function finds the second largest unique number from a list by converting it to a set, removing the maximum, and returning the new maximum.

set max unique
Python
def second_largest_unique(numbers):
    unique_numbers = set(numbers)
    if len(unique_numbers) < 2:
        return None
    unique_numbers.remove(max(unique_numbers))
    return max(unique_numbers)

if __name__ == "__main__":
    test_list = [4, 2, 9, 5, 2, 9, 1, 5]
    result = second_largest_unique(test_list)
    …
13 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 easy

Generate Pascal's Triangle Rows in Python

Builds Pascal's triangle as a list of rows, where each inner value is the sum of the two values above it.

pascal-triangle dynamic-programming algorithms
Python
def generate_pascals_triangle(rows):
    triangle = []
    for row_num in range(rows):
        row = [1] * (row_num + 1)
        for col in range(1, row_num):
            row[col] = triangle[row_num - 1][col - 1] + triangle[row_num - 1][col]
        triangle.append(row)
    return triangle

if __name__ == "__main__":
…
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 easy

How to Compare Two Lists Elementwise for Greater Flags in Python

Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.

lists comparison zip
Python
def compare_lists_greater(list_a, list_b):
    """
    Compare two lists elementwise and return a list of booleans
    indicating whether each element in list_a is greater than the
    corresponding element in list_b.
    """
    if len(list_a) != len(list_b):
        raise ValueError("Lists must have the same length"…
13 0 Open
Algorithms & data structures easy

How to Compute Jaccard Similarity in Python

Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.

jaccard sets similarity
Python
def jaccard_similarity(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    
    intersection = set1 & set2
    union = set1 | set2
    
    if not union:
        return 0.0
    
    return len(intersection) / len(union)

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5]
    b = [3, 4, 5, 6, 7]
    
    pri…
17 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.