Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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.
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…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
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.
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(…
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.
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…
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.
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
…
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.
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]:
…
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.
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…
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.
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…
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 []
…
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.
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…
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.
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[…
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.
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__ == …
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.
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:
…
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.
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…
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.
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…
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.