Reference library

Algorithms & data structures

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

35 matches
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 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 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 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 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
Algorithms & data structures easy

How to Count Distinct Elements in a List in Python

Count the number of unique items in a list by converting it to a set and returning its length.

set count unique
Python
def count_distinct_elements(items):
    return len(set(items))

if __name__ == "__main__":
    sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
    result = count_distinct_elements(sample)
    print(result)
14 0 Open
Algorithms & data structures easy

How to Generate a Geometric Progression List in Python

This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.

geometric-progression sequence algorithms
Python
def geometric_progression(first_term, ratio, count):
    """
    Generate a list of 'count' terms in a geometric progression
    starting with 'first_term' and multiplied by 'ratio' each step.
    """
    progression = []
    current = first_term
    for _ in range(count):
        progression.append(current)
        c…
13 0 Open
Algorithms & data structures easy

How to Get All Combinations of a List in Python

Generate and display all combinations of a given length from a list using Python's itertools.combinations.

itertools combinations list
Python
from itertools import combinations

def list_combinations(items, r):
    """Return all combinations of length r from a list."""
    return list(combinations(items, r))

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry", "date"]
    pick = 2
    result = list_combinations(fruits, pick)
    
    print…
12 0 Open
Algorithms & data structures easy

How to Implement a Moving Average from a Data Stream in Python

Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.

deque sliding-window streaming
Python
from collections import deque

class MovingAverage:
    def __init__(self, size):
        self.size = size
        self.queue = deque()
        self.window_sum = 0

    def next(self, val):
        self.queue.append(val)
        self.window_sum += val

        if len(self.queue) > self.size:
            self.window_su…
12 0 Open
Algorithms & data structures easy

How to Implement a Recent Counter with a Deque in Python

Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.

deque recents sliding-window
Python
from collections import deque
import time


class RecentCounter:
    def __init__(self):
        self.hits = deque()

    def ping(self, t: int) -> int:
        self.hits.append(t)
        while self.hits and self.hits[0] < t - 3000:
            self.hits.popleft()
        return len(self.hits)


if __name__ == "__mai…
11 0 Open
Algorithms & data structures easy

How to Remove Duplicates in Python Preserving Order

Removes duplicate items from a list while keeping the first occurrence order intact using a set for fast membership checks.

deduplication set list
Python
def remove_duplicates_preserving_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

if __name__ == "__main__":
    sample = [3, 1, 2, 1, 3, 4, 2, 5]
    unique_items = remove_duplicates_preserv…
14 0 Open
Algorithms & data structures easy

How to Rotate an Array by k Steps in Python

This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.

array rotation algorithms
Python
def rotate_array(nums, k):
    if not nums:
        return []
    n = len(nums)
    k = k % n
    return nums[-k:] + nums[:-k] if k else nums[:]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 2
    result = rotate_array(arr, k)
    print(f"Original: {arr}")
    print(f"Rotated by {k}: {result}")
13 0 Open
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 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 easy

Implement Queue Using Two Stacks in Python

Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.

queue stack data-structures
Python
class QueueUsingStacks:
    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def enqueue(self, value):
        self.stack_in.append(value)

    def dequeue(self):
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
  …
13 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.