Reference library

Algorithms & data structures

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

7 matches
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 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 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 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 easy

How to Flatten List of Dict Values in Python

This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.

flatten dictionaries lists
Python
def flatten_dict_values(dicts):
    flattened = []
    for d in dicts:
        for value in d.values():
            if isinstance(value, list):
                flattened.extend(value)
            else:
                flattened.append(value)
    return flattened


if __name__ == "__main__":
    data = [
        {"a": …
12 0 Open
Algorithms & data structures medium

Implement Insert Delete GetRandom O(1) in Python

Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.

randomized-set o1-lookup hash-map
Python
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_map = {}

    def insert(self, val):
        if val in self.index_map:
            return False
        self.index_map[val] = len(self.values)
        self.values.append(val)
        return True

    def delete(self…
12 0 Open
Algorithms & data structures easy

Sort list by multiple keys with tuple ordering in Python

Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.

sorting tuples lambda
Python
def sort_multi_key(data):
    # Sorts by surname, then age, then score descending
    return sorted(
        data,
        key=lambda person: (
            person['surname'].lower(),
            person['age'],
            -person['score']  # negative to reverse sort by score
        )
    )


if __name__ == "__main__"…
14 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.