Reference library

Algorithms & data structures

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

63 matches
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 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 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 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 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 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 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
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 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 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 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.