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