Reference library

Algorithms & data structures

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

74 matches
Algorithms & data structures easy

Bucket Numbers into Histogram Bin Counts in Python

Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.

histogram bins statistics
Python
from collections import Counter

def histogram_bins(numbers, num_bins):
    """Bucket numbers into histogram bin counts."""
    if not numbers:
        return []
    
    min_val = min(numbers)
    max_val = max(numbers)
    bin_width = (max_val - min_val) / num_bins
    
    # Handle edge case where all values are id…
17 0 Open
Algorithms & data structures easy

Count Smaller Elements to the Right in Python

Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.

brute-force nested-loops counting
Python
def count_smaller_elements(arr):
    """
    Return a list where result[i] is the number of elements 
    to the right of arr[i] that are smaller than arr[i].
    """
    result = []
    for i in range(len(arr)):
        count = 0
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[i]:
               …
14 0 Open
Algorithms & data structures easy

Depth First Search Traversal Order in Python

Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.

dfs graph traversal
Python
def dfs_order(adj, start):
    visited = set()
    order = []

    def dfs(node):
        visited.add(node)
        order.append(node)
        for neighbor in adj.get(node, []):
            if neighbor not in visited:
                dfs(neighbor)

    dfs(start)
    return order


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

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

Filter List to Keep Only Whitelist Values in Python

Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.

filtering sets list-comprehension
Python
def filter_whitelist(values, whitelist):
    """Return only values that are present in the whitelist set."""
    return [value for value in values if value in whitelist]

if __name__ == "__main__":
    raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
    allowed = {"apple", "banana", "date"}

…
11 0 Open
Algorithms & data structures easy

Find All Indices of a Target Value in a Python List

Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.

list index enumerate
Python
def find_all_indices(arr, target):
    return [i for i, value in enumerate(arr) if value == target]

if __name__ == "__main__":
    sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
    target = 2
    result = find_all_indices(sample_list, target)
    print(result)
13 0 Open
Algorithms & data structures easy

Find Common Elements in List of Lists in Python

Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.

counter intersection nested-lists
Python
from collections import Counter


def common_elements(list_of_lists):
    """Return elements present in every sublist."""
    if not list_of_lists:
        return []
    counts = Counter(list_of_lists[0])
    for sublist in list_of_lists[1:]:
        counts &= Counter(sublist)
    return list(counts.elements())


if _…
13 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 easy

Find Elements in One Python List but Not Another

Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.

list difference set membership filtering
Python
def difference_elements(a, b):
    """Return elements present in list a but not in list b."""
    set_b = set(b)
    return [item for item in a if item not in set_b]

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [2, 4, 6]
    result = difference_elements(a, b)
    print(f"A: {a}")
    print(f"B: {b…
14 0 Open
Algorithms & data structures easy

Find First Duplicate Index in Python

Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.

duplicate dictionary arrays
Python
def find_first_duplicate(arr):
    seen = {}
    for index, value in enumerate(arr):
        if value in seen:
            return index
        seen[value] = index
    return -1

if __name__ == "__main__":
    test_array = [3, 5, 2, 8, 5, 1, 2]
    result = find_first_duplicate(test_array)
    print(f"Array: {test_arr…
13 0 Open
Algorithms & data structures easy

Find Longest Consecutive Run in an Unsorted List in Python

Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.

set consecutive linear-scan
Python
def longest_run(nums):
    if not nums:
        return 0

    num_set = set(nums)
    longest = 0

    for num in num_set:
        # Only start counting from the smallest number in a sequence
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
 …
11 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 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 Single Number Appearing Once in Python

Count frequency of each number in a list and return the one that appears exactly once when all others appear twice.

counter frequency single-number
Python
from collections import Counter

def find_single_number(nums):
    counts = Counter(nums)
    for num, count in counts.items():
        if count == 1:
            return num
    return None

if __name__ == "__main__":
    nums = [4, 1, 2, 1, 2]
    result = find_single_number(nums)
    print(f"Single number in {nums} …
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 easy

Find the Equilibrium Index of a List in Python

Find every index in a list where the sum of elements to its left equals the sum to its right, using a single pass.

equilibrium-index prefix-sums arrays
Python
def find_equilibrium_indexes(arr):
    total = sum(arr)
    left_sum = 0
    indexes = []
    for i, num in enumerate(arr):
        total -= num
        if left_sum == total:
            indexes.append(i)
        left_sum += num
    return indexes

if __name__ == "__main__":
    test = [1, 2, 3, -1, 2, 3]
    result =…
13 0 Open
Algorithms & data structures easy

Find the First Index Where a Condition Is True in Python

Search any iterable for the first element matching a predicate and return its index, or -1 if none match.

search enumerate index
Python
def first_true_index(items, condition):
    """Return the first index where condition(item) is True, or -1 if none match."""
    for i, item in enumerate(items):
        if condition(item):
            return i
    return -1


if __name__ == "__main__":
    numbers = [1, 3, 5, 8, 10, 12]
    # Find first number greate…
12 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 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 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 Add Two Lists Elementwise in Python

Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.

list zip list-comprehension
Python
def elementwise_add(list1, list2):
    return [a + b for a, b in zip(list1, list2)]

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [10, 20, 30, 40]
    result = elementwise_add(list_a, list_b)
    print(result)
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.