Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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.
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)
…
How to Find the n Smallest Items in a Large List with heapq in Python
This code demonstrates how to efficiently extract the n smallest items from a large list using Python's heapq module and a manual max-heap approach.
import heapq
def n_smallest_iterable(data, n):
"""Return the n smallest items without loading the whole list."""
if n <= 0:
return []
return heapq.nsmallest(n, data)
def n_smallest_manual(data, n):
"""Return the n smallest using a heap, O(n log k) time."""
if n <= 0:
return []
…
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.
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…
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.