Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Binary Search for Ship Capacity in Python
Use binary search to find the minimum ship capacity that can transport all packages within a given number of days.
def ship_within_days(weights, days):
def can_ship(capacity):
current = 0
needed_days = 1
for weight in weights:
if current + weight > capacity:
needed_days += 1
current = 0
current += weight
return needed_days <= days
low …
Find Longest Increasing Subsequence Length in Python
Compute the length of the longest increasing subsequence in an array using dynamic programming.
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…
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.
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…
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.
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…
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.
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)
…
Game of Life Next State Grid in Python
Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.
def next_state(grid):
m, n = len(grid), len(grid[0])
new = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
total = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
…
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 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 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__ == …
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.
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…
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.
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]
…
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.
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 *…
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.