Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find Elements Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
Find First Duplicate Index in Python
Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.
def find_first_duplicate(arr):
seen = {}
for index, value in enumerate(arr):
if value in seen:
return index
seen[value] = index
return -1
if __name__ == "__main__":
test_array = [3, 5, 2, 8, 5, 1, 2]
result = find_first_duplicate(test_array)
print(f"Array: {test_arr…
Find Maximum Distance Between Identical Elements in Python
Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.
from collections import defaultdict
def max_distance_between_identical(nums):
first_occurrence = {}
max_dist = 0
for i, num in enumerate(nums):
if num in first_occurrence:
dist = i - first_occurrence[num]
max_dist = max(max_dist, dist)
else:
first_occur…
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(…
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…
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.