Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

24 matches
Algorithms & data structures medium

Container With Most Water: Two-Pointer Solution in Python

Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.

two-pointer array algorithm
Python
from typing import List

def max_water_container(heights: List[int]) -> int:
    left, right = 0, len(heights) - 1
    max_area = 0
    
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        area = width * height
        max_area = max(max_area, area)
        …
15 0 Open
Algorithms & data structures medium

Find All Triplets with Sum Zero in Python

This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.

triplets two-pointers sorting
Python
def find_triplets(nums):
    nums.sort()
    n = len(nums)
    triplets = []
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
    …
14 0 Open
Algorithms & data structures medium

Find Longest Consecutive Sequence in Python

Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.

set longest-sequence hash-table
Python
def longest_consecutive_length(nums):
    num_set = set(nums)
    longest = 0
    
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            current_streak = 1
            
            while current + 1 in num_set:
                current += 1
                current_streak += 1
…
13 0 Open
Algorithms & data structures medium

Find Longest Increasing Subsequence Length in Python

Compute the length of the longest increasing subsequence in an array using dynamic programming.

dynamic-programming subsequence algorithm
Python
def longest_increasing_subsequence(nums):
    if not nums:
        return 0
    
    dp = [1] * len(nums)
    
    for i in range(1, len(nums)):
        for j in range(i):
            if nums[i] > nums[j]:
                dp[i] = max(dp[i], dp[j] + 1)
    
    return max(dp)

if __name__ == "__main__":
    # Demo with…
15 0 Open
Algorithms & data structures medium

Find Minimum in Rotated Sorted List in Python

Uses binary search to find the minimum element in a rotated sorted list in O(log n) time.

binary-search minimum rotated-array
Python
def find_min(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[right]:
            left = mid + 1
        else:
            right = mid
    return nums[left]


if __name__ == "__main__":
    rotated = [4, 5, 6, 7, 0, 1, 2]
    print(f"Minimu…
12 0 Open
Algorithms & data structures medium

Find Peak Element in Python Using Binary Search

A binary search solution that finds any peak element (an element strictly greater than its neighbors) in an unsorted array in O(log n) time.

binary-search peak array
Python
def find_peak_element(nums):
    left, right = 0, len(nums) - 1
    
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[mid + 1]:
            right = mid
        else:
            left = mid + 1
            
    return left

if __name__ == "__main__":
    test1 = [1, 2, 3, 1]
    tes…
17 0 Open
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Algorithms & data structures medium

Find the Majority Element in Python with Boyer-Moore Vote

Use Boyer-Moore majority vote to find the element appearing more than n/2 times in an array in O(n) time and O(1) space.

boyer-moore majority-element array
Python
def majority_element(nums):
    candidate = None
    count = 0

    for num in nums:
        if count == 0:
            candidate = num
        count += 1 if num == candidate else -1

    return candidate

if __name__ == "__main__":
    nums = [2, 2, 1, 1, 1, 2, 2]
    result = majority_element(nums)
    print(f"Major…
14 0 Open
Algorithms & data structures medium

Find two unique numbers in an array with Python

Returns the two numbers that appear exactly once in a list where every other number appears twice, using XOR bit manipulation.

bit-manipulation xor arrays
Python
def find_two_odd(arr):
    """Return the two numbers that appear exactly once, while all others appear twice."""
    xor_all = 0
    for num in arr:
        xor_all ^= num

    # xor_all now equals the XOR of the two unique numbers.
    # Find a set bit (any bit where they differ).
    diff_bit = xor_all & (-xor_all)
…
13 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 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 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

Product of All Elements Except Self in Python

Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.

array prefix suffix
Python
def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]
    
    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *= nums[i]
    
…
14 0 Open
Algorithms & data structures medium

Product of Array Except Self in Python Without Division

Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.

arrays prefix-product suffix-product
Python
from math import prod


def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]

    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *…
14 0 Open
Algorithms & data structures medium

Set Matrix Zeroes in Python: Markers List Grid Demo

Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.

matrix arrays algorithm
Python
def set_zeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    row_markers = [False] * rows
    col_markers = [False] * cols

    # First pass: record which rows and columns contain zeros
    for i in range(rows):
        for j in range(cols):
            if matrix[i][j] == 0:
                row_markers[i] …
14 0 Open
Algorithms & data structures medium

Split Array Largest Sum in Python (Minimize Largest Subarray Sum)

Binary search + greedy check to split an array into k subarrays while minimizing the largest subarray sum.

binary-search greedy array
Python
def can_split(nums, k, max_sum):
    subarrays = 1
    current_sum = 0
    for num in nums:
        if current_sum + num <= max_sum:
            current_sum += num
        else:
            subarrays += 1
            current_sum = num
            if subarrays > k:
                return False
    return True

def spli…
15 0 Open
Comprehensions & generators medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 0 Open
Concurrency & performance medium

How to Share Memory Between Processes in Python with multiprocessing.Value and Array

Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.

multiprocessing shared-memory concurrency
Python
import multiprocessing

def worker(shared_value, shared_array, index):
    shared_value.value += 10
    shared_array[index] = shared_array[index] * 2

if __name__ == "__main__":
    shared_value = multiprocessing.Value("i", 5)
    shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])

    processes = []
    for i…
13 0 Open
API design & gRPC medium

Build a Bulk Array POST Mock Server in Python

Creates an HTTP mock server that accepts POST requests with a JSON array and returns incremental IDs for each item.

http-server mock-api rest
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse

class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if urlparse(self.path).path != "/bulk":
            self.send_response(404)
            self.end_headers()
            return

        cont…
15 0 Open
A/B testing & experimentation medium

How to Generate an Orthogonal Array for A/B Testing in Python

Generate a mock orthogonal array for multi-layer experiments with NumPy, ensuring balanced level combinations across experiment groups.

ab-testing orthogonal-array numpy
Python
import numpy as np

def orthogonal_mock_layers(n_experiments: int, n_layers: int, n_levels: int) -> np.ndarray:
    """Generate an orthogonal array for multi-layer experiment design using base-level logic."""
    ortho = np.indices((n_levels,) * n_layers).reshape(n_layers, -1).T
    ortho = ortho % n_levels  # Classic…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.