Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find Longest Consecutive Run in an Unsorted List in Python
Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.
def longest_run(nums):
if not nums:
return 0
num_set = set(nums)
longest = 0
for num in num_set:
# Only start counting from the smallest number in a sequence
if num - 1 not in num_set:
current = num
length = 1
while current + 1 in num_set:
…
Find Longest Consecutive Sequence in Python
Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.
def longest_consecutive_length(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current = num
current_streak = 1
while current + 1 in num_set:
current += 1
current_streak += 1
…
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 Median of Two Sorted Arrays in Python
Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.
def median_of_two_sorted_arrays(nums1, nums2):
merged = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.…
Find Missing Number in Python Sequence 1 to N
Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.
def find_missing_number(nums, n):
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
if __name__ == "__main__":
n = 10
numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
missing = find_missing_number(numbers, n)
print(f"The missing number is: {missing}")
Find the Last Index Where a Condition Is True in Python
This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.
def last_index_where(sequence, condition):
"""Return the index of the last element in sequence that satisfies condition."""
for i in range(len(sequence) - 1, -1, -1):
if condition(sequence[i]):
return i
return -1
if __name__ == "__main__":
numbers = [1, 4, 7, 2, 9, 5, 8, 3]
is_…
How to Generate Fibonacci Sequence in Python
Generate the first n Fibonacci numbers as a list using a simple iterative loop.
def fibonacci(n):
"""Generate the first n terms of the Fibonacci sequence."""
if n <= 0:
return []
seq = [0, 1]
while len(seq) < n:
seq.append(seq[-1] + seq[-2])
return seq[:n]
if __name__ == "__main__":
n = 10
result = fibonacci(n)
print(result)
How to Generate a Geometric Progression List in Python
This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.
def geometric_progression(first_term, ratio, count):
"""
Generate a list of 'count' terms in a geometric progression
starting with 'first_term' and multiplied by 'ratio' each step.
"""
progression = []
current = first_term
for _ in range(count):
progression.append(current)
c…
How to Generate an Arithmetic Progression List in Python
Generates a list of terms in an arithmetic progression using a list comprehension.
def generate_ap(start, difference, count):
"""Generate a list of n terms in an arithmetic progression."""
return [start + i * difference for i in range(count)]
if __name__ == "__main__":
ap = generate_ap(3, 5, 6)
print(ap)
How to Sample Random Items Without Replacement in Python
Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.
import random
def sample_without_replacement(population, k):
"""Return k random items from population without replacement."""
if k > len(population):
raise ValueError("k cannot exceed population size")
# Use random.sample for O(k) time, no mutation of the original
return random.sample(populati…
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:
…
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.