Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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.
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…
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)
…
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 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:
…
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 *…
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.
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] …
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.