Reference library

Algorithms & data structures

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

11 matches
Algorithms & data structures easy

How to Combine filter and map with a List Comprehension in Python

This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.

list-comprehension filter map
Python
def square(x):
    return x * x

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

result = [square(x) for x in numbers if is_even(x)]

print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")

# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
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…
12 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
…
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 Map Strings to Uppercase in Python

Loops through a list of strings and builds a new list with each string converted to uppercase.

string loop uppercase
Python
strings = ["hello", "world", "python", "skillset"]

uppercased = []
for s in strings:
    uppercased.append(s.upper())

print(uppercased)
13 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…
13 0 Open
Algorithms & data structures easy

How to Replace Outliers Beyond Threshold with Cap in Python

Replace values that fall below a lower threshold or above an upper threshold by capping them to the threshold values using a simple Python function.

outliers capping data-cleaning
Python
def replace_outliers_with_cap(data, lower_threshold=None, upper_threshold=None):
    """Replace values beyond given thresholds with the threshold values (capping)."""
    if lower_threshold is None and upper_threshold is None:
        raise ValueError("At least one threshold must be provided.")
    
    capped_data = …
11 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:
         …
16 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…
11 0 Open
Algorithms & data structures easy

Insert Multiple Values Into a Sorted List in Python

Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.

bisect sorted-list insertion
Python
import bisect

def insert_sorted(sorted_list, values):
    for value in values:
        bisect.insort(sorted_list, value)
    return sorted_list

if __name__ == "__main__":
    original = [1, 3, 5, 7, 9]
    new_values = [4, 6, 2, 8, 0]
    result = insert_sorted(original, new_values)
    print(f"Original: {original}"…
13 0 Open
Algorithms & data structures easy

Pair Elements with Next Cyclic Neighbor in Python

Create tuples pairing every element with its next element, wrapping around to the first element for the last one.

pairs cyclic list
Python
def cyclic_pairs(lst):
    if not lst:
        return []
    return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5]
    result = cyclic_pairs(sample)
    print(result)
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.