Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Filter List to Keep Only Whitelist Values in Python
Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.
def filter_whitelist(values, whitelist):
"""Return only values that are present in the whitelist set."""
return [value for value in values if value in whitelist]
if __name__ == "__main__":
raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
allowed = {"apple", "banana", "date"}
…
Find k Closest Points to Origin in Python
Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.
import math
def k_closest(points, k):
points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
return points[:k]
if __name__ == "__main__":
points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
k = 3
result = k_closest(points, k)
print(f"Original points: {points}")
print(f"K closest points (k…
How to Compute Cosine Similarity Between Two Vectors in Python
This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.
import math
def cosine_similarity(vec_a, vec_b):
if len(vec_a) != len(vec_b):
raise ValueError("Vectors must have the same length")
dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
norm_a = math.sqrt(sum(a * a for a in vec_a))
norm_b = math.sqrt(sum(b * b for b in vec_b))
i…
How to Find the Nearest Value to a Target in a Sorted List in Python
Use bisect to binary-search a sorted list and return the element closest to a target value.
import bisect
def nearest_value(sorted_list, target):
if not sorted_list:
return None
pos = bisect.bisect_left(sorted_list, target)
if pos == 0:
return sorted_list[0]
if pos == len(sorted_list):
return sorted_list[-1]
before = sorted_list[pos - 1]
after = sorted_list[po…
How to Rotate an Array by k Steps in Python
This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.
def rotate_array(nums, k):
if not nums:
return []
n = len(nums)
k = k % n
return nums[-k:] + nums[:-k] if k else nums[:]
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
k = 2
result = rotate_array(arr, k)
print(f"Original: {arr}")
print(f"Rotated by {k}: {result}")
Insert an Element Every n Positions in Python
Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.
def insert_every_n(seq, element, n, position="after"):
"""Insert an element before or after every n-th position in a list.
Args:
seq: Input list
element: Element to insert
n: Insert every n positions (n > 0)
position: 'before' or 'after' (default: 'after')
Returns:
…
Merge Two Sorted Arrays Without Extra Space in Python
Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.
def merge_sorted(arr1, arr2):
m, n = len(arr1), len(arr2)
i, j = m - 1, n - 1
while j >= 0:
if i >= 0 and arr1[i] > arr2[j]:
arr1[i + j + 1] = arr1[i]
i -= 1
else:
arr1[i + j + 1] = arr2[j]
j -= 1
return arr1
if __name__ == "__main__":
…
Segregate Negative Numbers Before Positives in Python
Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.
def segregate_negatives(numbers):
"""Segregate negatives before positives without altering relative order."""
negatives = [n for n in numbers if n < 0]
positives = [n for n in numbers if n >= 0]
return negatives + positives
if __name__ == "__main__":
sample = [3, -1, 4, -5, 2, -9, 0]
result =…
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.