Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find the Duplicate Number in Python Using Floyd's Cycle Detection
Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.
def find_duplicate(nums):
slow = nums[0]
fast = nums[0]
# Phase 1: Find intersection point of the cycle
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# Phase 2: Find the start of the cycle (the duplicate)
slow = nums[0…
How to Find Minimum Swaps to Sort an Array in Python
Calculate the minimum number of adjacent-free swaps needed to sort a permutation array using cycle detection in Python.
def min_swaps_to_sort(arr):
n = len(arr)
arr_pos = sorted((val, idx) for idx, val in enumerate(arr))
visited = [False] * n
swaps = 0
for i in range(n):
if visited[i] or arr_pos[i][1] == i:
continue
cycle_size = 0
j = i
while not visited[j]:
…
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.