FizzBuzz, precisely
Return a newline-separated string for 1..n: Fizz, Buzz, FizzBuzz, or the number.
Temperature converter
Convert Celsius to Fahrenheit: F = C × 9/5 + 32.
Even or odd?
Return 'even' or 'odd' for an integer.
Sum of digits
Return the sum of all decimal digits of a non-negative integer.
Collatz steps
Count how many steps the Collatz sequence takes to reach 1 from n.
Factorial (iterative)
Compute n! iteratively without recursion.
Power of two?
Return True if n is an exact power of 2.
GCD via Euclid
Compute the greatest common divisor of two positive integers.
Fibonacci(n)
Return the nth Fibonacci number efficiently.
Prime checker
Return True if n is a prime number.
Compound interest
Return the future balance after compound interest, rounded to two decimals.
Clamp a Number to a Range
Implement a clamp function that returns a value within a specified range.
Absolute Difference of Two Integers
Compute the absolute difference between two integers, regardless of order.
Leap Year Checker
Implement a function that decides whether a year is a leap year according to the standard Gregorian rules.
Grade from Score
Write a function that maps a numeric score to its letter grade using standard grading thresholds.
Min of three numbers
Write a function that returns the minimum of three integers.
Integer division and remainder
Write a function that performs integer division and returns both quotient and remainder.
Count down from n
Implement a function that returns a list from n down to 1.
Sum numbers from 1 to n
Implement a function that computes the sum of all integers from 1 to n.
Multiplication Table Row
Return the nth row of a multiplication table as a list of 1..n products.
Sign of a Number
Write a function that returns the sign of a number as a string.
Seconds to Hours Minutes Seconds
Convert total seconds into a zero-padded HH:MM:SS format.
Is a multiple of both
Write a function that returns True if a number is divisible by both of two given divisors.
Digit count of an integer
Given an integer, return the number of digits it has, handling negatives and zero correctly.
Boolean from comparison chain
Implement a function that evaluates a chain of comparisons and returns the boolean result.
Max of a variable-length list
Implement a function that returns the maximum value from a list of numbers without using max().
Classify triangle by sides
Write a function that classifies a triangle based on three side lengths.
Toggle a boolean n times
Apply boolean toggling n times and return the final boolean value.
Between inclusive
Write a function that returns True if a number is between two given bounds, inclusive of the bounds.
Last Occurrence of a Value
Implement a function that returns the last index of a given value in a list, or -1 if it's not present.
Cycle a List Once
Implement a function that rotates a list right by one position.
Boolean Mask Filter
Write a function that filters a list based on a boolean mask and returns the selected elements.
Replace negatives with zero
Implement a function that replaces all negative numbers in a list with zero.
Set symmetric difference
Write a function that returns the elements found in exactly one of two sets, sorted ascending.
Swap Two Values
Implement a Python function that swaps two given values and returns them in swapped order.
Count Multiples in a Range
Given a start, end, and divisor, count how many integers in [start, end] are divisible by the divisor.
Hello, name!
Implement a function that returns a personalized greeting for a given name.
Leap Year Checker
Implement a function that returns True if a year is a leap year according to the Gregorian calendar rules.
Grade Calculator
Implement a function that converts a numeric score to a letter grade using a standard scale.
Minutes to Hours: Time Conversion Helper
Write a function that converts minutes into a human-readable 'Xh Ym' string, with special cases for zero and whole hours.
Simple Interest Calculator
Implement a function that calculates simple interest given principal, annual rate, and time in years.
Tip Calculator
Write a function that calculates the total bill after adding a given tip percentage.
Absolute Difference
Implement a function that returns the absolute difference between two numbers.
Max of three numbers
Implement a function that returns the maximum of three numbers using comparisons.
Sign of a number
Write a function sign_of_number that returns -1 for negatives, 0 for zero, and 1 for positives.
Countdown printer
Implement a function that prints a countdown from a given number down to 1, then returns 'Go!'.
Sum from 1 to n
Write a function that returns the sum of all integers from 1 to n (inclusive).
Average of a list
Write a function that computes the average of a list of numbers, handling empty lists by returning 0.
Count Positives
Count the positive numbers in a list of integers.
Find Minimum Value
Write a function that returns the minimum integer from a given list.
Range of values
Calculate the range (max minus min) of a list of numbers. Empty list returns 0.
Is divisible by?
Create a function that returns True if a is divisible by b with no remainder, with a clear definition of edge cases.
Round to nearest ten
Write a function that rounds any integer to the nearest multiple of ten.
Fahrenheit to Celsius
Implement a function that converts degrees Fahrenheit to degrees Celsius.
Speed Converter
Write a function to convert speeds between kilometers per hour and meters per second.
Area of Rectangle
Write a function that returns the area of a rectangle given its width and height.
Perimeter of triangle
Given three side lengths, return the perimeter (sum) of the triangle.
Circle Circumference Calculator
Implement a function that computes the circumference of a circle from its radius using the formula 2πr.
Volume of Cube
Write a Python function that returns the volume of a cube given its side length.
Modulo Remainder
Implement a function that returns the remainder of a divided by b without using the modulo operator.
Print Pyramid Pattern
Implement a function that returns a centered asterisk pyramid as a list of strings.
Digit Count
Count the number of digits in an integer using arithmetic, without string conversion.
Last Digit Extractor
Write a function that returns the last digit of a non-negative integer using the modulo operator.
Count word occurrences
Write a function that takes a sentence and returns a dictionary of word counts.
Find Missing Number
Given a list of n distinct integers from 0..n with one missing, return the missing number.
Map, Filter, Reduce
Implement three functions using map, filter, and reduce to manipulate a list of integers.
Variadic Sum Function
Implement a variadic function that sums an arbitrary number of numeric arguments.
Linear Search Implementation
Implement a linear search function that returns the index of the first occurrence of a target in a list, or -1 if not found.
Pathlib Operations: File Path Basics
Practice using pathlib to manipulate file paths and extract components.
Garbage Collection Hint
Write a function that predicts when an object is garbage collected based on reference counting.
Enumerate with start
Implement a function that mimics Python's enumerate with a custom start index.
Validate date format
Return True if input string is exactly YYYY-MM-DD and a real calendar date.
Palindromic Number Check
Write a function to check if a given integer is a palindrome.
Hexagonal Number
Write a function to check if a positive integer is a hexagonal number.
Count trailing zeros
Write a function that counts the number of trailing zeros in the decimal representation of a positive integer.
Count Leading Zeros
Write a function that returns the number of leading zeros in a list of integers.
Reverse a string
Return the characters of the string in reverse order.
Palindrome check
Return True if the string reads the same forwards and backwards (ignoring case and non-alphanumeric).
Count vowels
Count the number of vowels (a, e, i, o, u) in a string (case-insensitive).
Title case converter
Return the string with each word capitalised.
Anagram check
Return True if two strings are anagrams of each other.
Run-length encoding
Compress consecutive identical characters, e.g. 'aaabbc' → 'a3b2c1'.
Longest common prefix
Find the longest common prefix among a list of strings.
Integer to Roman
Convert a positive integer to its Roman numeral representation.
Zigzag string conversion
Encode a string in zigzag order across numRows rows, then read row by row.
Strip and Collapse Whitespace
Write a function that strips leading/trailing whitespace and collapses inner runs of whitespace to single spaces.
Snake case to camel case
Implement a function that converts snake_case strings to camelCase.
Camel case to snake case
Write a function that converts camelCase input to snake_case while handling acronyms and numbers correctly.
Remove punctuation
Write a function that removes all ASCII punctuation characters from a string.
Is pangram
Write a function that determines whether a given string is a pangram, ignoring case and non-letter characters.
Caesar Cipher Shift
Implement a function to apply a Caesar cipher shift to a string, preserving case and ignoring non-letters.
Repeat each character n times
Given a string s and an integer n, return a new string where each character of s is repeated n times consecutively.
Longest word in a sentence
Write a function that returns the longest word from a sentence, with first-occurrence tie-breaking.
Replace vowels with stars
Write a function that replaces every vowel in a given string with an asterisk.
Is isogram
Implement a function that determines whether a string is an isogram (no repeated letters, case-insensitive).
Extract Digits Only
Given a string that may contain letters, symbols, and whitespace, extract all digits in order and return them as an integer.
Kebab Case a Phrase
Implement a function that converts a phrase into lowercase kebab-case, handling spaces, punctuation, and camelCase.
Normalize quotes
Replace all typographic quote characters with straight ASCII quotes.
Find all indexes of a substring
Write a function that returns a list of all starting indexes where a substring appears in a string, including overlapping occurrences.
Remove Consecutive Duplicate Letters
Implement a function that removes consecutive duplicate letters from a string, keeping only one occurrence of each run.
Interleave Two Strings
Given two strings s1 and s2, return a new string that interleaves them character by character, starting with s1.
Is rotation of another string
Write a function to determine if one string is a rotation of another string.
Sort characters alphabetically
Sort all characters in a string alphabetically and return the sorted string.
Initials from a Full Name
Return the uppercase initials of each word in a given full name.
Count words in a sentence
Implement a function to count words in a sentence, ignoring extra whitespace and handling empty strings.
Center a string in a width
Write a function that centers a string within a specified width by adding spaces on both sides.
Caesar Cipher Shift
Write a function that shifts letters in a string by a given amount, preserving case and ignoring non-letters.
Reverse Words in a Sentence
Reverse the order of words in a sentence while preserving single spaces between words.
Count consonants
Write a function that counts the number of consonant letters in a string.
Is pangram?
Implement is_pangram(s) to return True if the string contains every letter from 'a' to 'z' at least once, ignoring case and non-alphabetic characters.
Remove Duplicates from String
Given a string, return a new string with each character that repeats consecutively reduced to a single occurrence.
Longest Word Finder
Write a function that extracts alphabetic words from a string and returns the longest one, with ties broken by earliest position.
Abbreviate Name
Create a function that takes a full name and returns an abbreviated version with initials and the last name.
Mask email address
Given an email address, return a masked version that hides everything but the first and last character of the local part and the domain.
Extract digits from string
Write a function that extracts all digit characters from a given string, preserving their original order.
Replace Spaces with Dashes
Write a function that replaces every space in a string with a dash.
Capitalize First Letter
Write a function that capitalizes the first letter of each word in a string.
Snake case converter
Implement a function that converts a string to snake_case according to given rules.
Camel Case Converter
Write a function that converts a space-separated phrase into lower camelCase.
Kebab Case Converter
Implement a function that converts any string to kebab-case, handling spaces, underscores, camelCase, and punctuation.
Count Syllables (Simple)
Count syllables in a word by counting groups of consecutive vowels (a, e, i, o, u).
Is isogram?
Write a function that checks whether a given word is an isogram, ignoring letter case and only considering alphabetic characters.
Rotate String Right
Implement a function that rotates a given string to the right by a specified number of positions, handling shifts larger than the string length.
Compress Consecutive Chars
Write a function that compresses a string by replacing runs of identical characters with the character followed by the count.
Expand compressed string
Implement a function that expands run-length encoded strings (e.g., 'a3b2' → 'aaabb').
Find substring index
Implement a function that returns the starting index of the first occurrence of a substring using only basic string indexing and slicing.
Count Substrings
Implement a function that counts non-overlapping occurrences of a substring in a given string.
Sort characters in string
Write a function that sorts the characters in a string and returns the sorted string.
Most Common Character
Return the character that appears most frequently in a string, breaking ties by earliest occurrence.
Roman to Integer
Convert a valid Roman numeral string to an integer using standard rules.
Isomorphic Strings Check
Given two strings, check if they are isomorphic by verifying a one-to-one character mapping.
Find all anagrams
Return all starting indices where any anagram of a given word appears as a substring.
Substring Anagrams
Return all start indices in a string where a substring of length k is an anagram of a pattern string.
Longest Palindrome Substring
Given a string s, return the longest substring that reads the same forwards and backwards.
Index of First Occurrence
Implement a function that finds the starting index of a substring within a string, returning -1 when absent.
Safe Command Executor
Implement emulate_run that simulates running a command list and returns output and exit code.
Error message formatter
Write a function that constructs a formatted error message from a code, an optional context, and a fallback message.
Stack Trace Sanitizer
Implement a function that rewrites traceback file paths to basenames only.
Extract Hashtags
Extract unique hashtags from a given text string in the order they appear.
Extract mentions
Extract unique @mentions from a string, respecting email-like patterns and punctuation.
Validate time format
Check whether a given string is a valid 24-hour time in HH:MM format.
Parse Log Line
Write a function that parses a log line and returns a dictionary with timestamp, level, and message.
Replace multiple spaces
Implement a function that replaces every sequence of spaces with a single space.
Remove HTML tags
Remove all HTML tags from a string to extract clean text.
Extract Quoted Strings
Write a function that extracts the text inside every double-quoted substring from a given string.
Split on camelCase
Given a camelCase string, split it into words at uppercase letters and return them as lowercase words.
Extract domain from URL
Extract the domain (hostname without port or www) from a given URL string.
Normalize Whitespace
Write a function that normalizes any whitespace in a string to single spaces and trims the ends.
Strip Leading Zeros
Write a function that strips leading zeros from a string representing a non-negative integer.
Parse key=value pairs
Implement a parser that converts a space-separated 'key=value' string into a Python dictionary, supporting quoted values.
Find all numbers in text
Write a function that extracts all standalone integers from a text string using regular expressions.
Extract file extensions
Implement a function that extracts the extension from a filename according to standard rules.
Validate username format
Implement a function that validates a username according to length, allowed characters, and no consecutive underscores.
Replace template variables
Implement a function that replaces {{variable}} placeholders in a string using a dictionary, leaving unknown placeholders intact.
Hamming Distance
Implement a function that computes the Hamming distance between two strings of equal length.
Two Sum
Return indices (i, j) with i < j such that nums[i] + nums[j] == target.
Maximum subarray (Kadane)
Find the contiguous subarray with the largest sum.
Rotate array
Rotate a list right by k positions in place.
Flatten nested list
Yield every integer from an arbitrarily nested list, depth-first.
Remove duplicates (sorted)
Return a sorted list with duplicates removed.
Merge two sorted arrays
Merge two sorted arrays into one sorted array.
Merge intervals
Merge all overlapping intervals and return a sorted result.
Product except self
Return an array where output[i] is the product of all elements except nums[i], without using division.
Sliding window maximum
Return the maximum of each window of size k as it slides across an array.
Running Product of Integers
Given a list of integers, return a new list where each element at index i is the product of all elements from index 0 to i.
Second Largest Unique Value
Return the second largest distinct integer from a list, or None if it doesn't exist.
Move Zeros to the End
Reorder a list in-place, pushing all zeros to the end while preserving the order of non-zero numbers.
Chunk a list into n-sized parts
Write a function that divides a list into sublists of at most n elements.
Rotate Left by k
Implement a function that rotates a list left by k positions.
Find Missing Number 1 to n
Given a list containing n-1 distinct integers from 1 to n, find the missing number without using extra space.
Product of All Except Zeros Handling
Given a list of integers, return a list where each element is the product of all other elements, handling zeros correctly.
Interleave Two Lists
Write a function that interleaves two lists element by element, preserving order.
Keep only even indexes
Given a list, return a new list containing only the elements at even indices (0, 2, 4, ...).
Running Maximum
Implement a function that returns a list where each element is the largest value seen so far.
Difference of Consecutive Elements
Given a list of numbers, return a new list where each element is the difference between consecutive elements.
All Unique Values Keep Order
Remove duplicates from a list, keeping only the first occurrence of each value while preserving relative order.
Partition around a pivot value
Implement an in-place partition of a list around a given pivot value, returning the boundary index.
Insert into a Sorted List
Implement a function that inserts a value into a sorted list at the correct position using binary search.
Average excluding min and max
Return the average of a list after discarding the lowest and highest elements, handling edge cases.
Zip lists into pairs
Write a function that takes two lists and returns a list of two-element sublists pairing elements by index up to the shortest length.
Longest Run of Equal Values
Compute the length of the longest run (consecutive block) of equal elements in a list.
Middle Element of an Odd-Length List
Implement a function that returns the middle element of an odd-length list.
Is Subset of Another List
Write a function that returns True if every element in a given list exists in another list, ignoring duplicates.
Unzip pairs into two lists
Write a function that takes a list of pairs and returns two separate lists: first elements and second elements.
Generate a Multiplication Table
Build a function that returns an n x n multiplication table as a list of lists.
Find Second Largest
Find the second largest unique number in a list, or None if it doesn't exist.
Move Zeros to End
Rearrange a list by moving all zeros to the end while preserving the relative order of non-zero elements.
Majority Element Finder
Implement a function that returns the majority element in a list, which appears more than half the time.
Find Duplicate Number
Given a list of n+1 integers in the range 1..n, find the one integer that appears more than once.
Intersection of Two Lists
Given two lists, return a sorted list of unique elements that appear in both lists.
Union of Two Lists
Implement a function that combines two lists and returns only unique elements.
Difference of Two Lists
Write a function that returns items in list a that are not in list b, preserving order and duplicates.
Chunk list into groups
Implement a function that splits a list into sublists of a given size.
Zip Two Lists
Write a function that pairs elements from two lists by index, stopping at the shorter list.
Partition Array
Implement a function that finds a contiguous partition of a list into k groups, minimizing the maximum sum of the groups.
Rearrange Positives and Negatives
Write a function that rearranges a list in-place so all negative numbers come before non-negative numbers.
Wave sort array
Given a list of integers, reorder it into a wave pattern where elements alternate down-up, and return the new list.
Last occurrence index
Implement a function that returns the last index of a given value in a list, or -1 if the value is not present.
Counting Sort
Implement the counting sort algorithm to sort a list of non-negative integers in O(n + k) time.
Two Missing Numbers
Given a list of n-2 unique integers from 1 to n, find the two missing numbers efficiently.
Three Missing Numbers
Find the three missing numbers from a shuffled list containing all but three integers from 1 to n.
Word frequency
Return a dict mapping each word to its count in the sentence.
List intersection
Return the sorted list of elements common to both lists.
Group anagrams
Group words that are anagrams of each other.
First non-repeating character
Find the index of the first character that appears only once.
Most frequent element
Return the element that appears most often in a list.
Subarray sum equals K
Count the number of contiguous subarrays whose sum equals k.
Merge dicts summing values
Write a function that merges two dictionaries by summing values for duplicated keys.
Are two lists the same multiset
Write a function that checks if two lists contain the same elements with the same multiplicities, ignoring order.
Word to Index Map
Create a function that returns a dictionary mapping each unique word to the index of its first occurrence.
Group names by first letter
Given a list of names, return a dictionary mapping each first letter to all names starting with that letter in original order.
Missing keys default zero
Write a function to sum numeric values from dictionaries, treating missing keys as zero.
Keys Sorted by Value Descending
Given a dictionary mapping strings to integers, return a list of keys sorted by value descending, and when values tie, alphabetically ascending.
Nested get with dotted path
Implement a function that safely retrieves a value from a deeply nested dictionary using a dot-separated path, returning a default if any key is missing.
Anagram Dictionary Groups Lite
Group a list of words into anagrams using a dictionary keyed by sorted characters.
Common Keys of Two Dictionaries
Implement a function that finds keys shared by two dictionaries and returns them sorted.
Union of Many Sets
Implement a function that takes any number of sets and returns a sorted list of their union.
Mode of a list via counting
Implement a function that returns the mode of a list, resolving ties by the element that appears first.
Top k keys by count
Given a dictionary mapping keys to counts, return the top k keys with the highest counts, breaking ties alphabetically.
Values that appear once
Return a list of numbers that appear exactly once in the input list, in original order.
Replace keys with a mapping
Write a function that renames keys in a dictionary according to a mapping, with duplicate handling.
Two Sum with Dict
Implement the classic Two Sum problem: return indices of two numbers that add up to a target using a dict.
Anagram Groups by Size
Group a list of words into anagram groups and return them sorted by group size and lexicographically.
Top K Frequent Words
Given a list of words, return the k most frequent words sorted by frequency (descending) and then alphabetically.
Sort by frequency
Sort a list by element frequency descending, with ties broken by order of first occurrence.
Pair with difference K
Count unordered index pairs with absolute difference exactly K, handling duplicates correctly.
Set intersection size
Count how many distinct values appear in both of two given lists.
Symmetric Difference
Write a function that computes the symmetric difference of two lists, returning a sorted list of unique elements.
Disjoint Set Check
Check if two lists are disjoint by verifying they have no common elements.
Subset of another set
Write a function that checks if every element of one set is contained in another.
Frequency sort descending
Write a function that sorts a list by frequency descending while preserving original order for ties.
Count Pairs with Sum
Implement a function that counts the number of distinct pairs in a list summing to a target.
Hash map merge
Write a function that merges two dictionaries recursively, combining values and preserving structure.
Ransom Note Builder
Given two strings, determine if the ransom note can be formed from the words in the magazine.
Memoize decorator
Implement a @memoize decorator that caches results of a function.
Function composition
Return a function that applies f after g: compose(f, g)(x) == f(g(x)).
Curry a function
Auto-curry any multi-argument function so it returns partial applications until fully saturated.
Bind First Argument
Implement bind_first_arg, a decorator that fixes the first argument of any function.
Stack class
Implement a Stack class with push, pop, peek, is_empty, and size.
Linked list reversal
Implement a singly linked list and a function to reverse it in place.
Matrix addition operator
Implement a Matrix class that supports + and * operators.
Event emitter basics
Implement an EventEmitter class with subscribe/emit/unsubscribe functionality.
Rectangle class
Implement a Rectangle class with properties, methods, and special methods for basic geometry and comparison.
Complex Number Class
Implement a Complex class supporting addition, subtraction, multiplication, division, equality, and string formatting.
Queue class (list-based)
Implement a Queue class with enqueue, dequeue, peek, is_empty, and is_full methods using a list.
Comparable mixin
Create a Comparable mixin that auto-generates all rich comparison operators from a single __lt__ method.
Class Method Factory
Create a class method factory that dynamically adds methods to a class based on a mapping of names to behaviors.
Abstract Base Class
Create an abstract Shape class and implement Rectangle and Circle subclasses with area and perimeter.
Reentrant Lock Manager
Implement a ReentrantLock class with acquire, release, locked, owner, and helper functions that test thread-safety with real threads.
Valid parentheses
Return True if brackets in the string close in the correct order.
Binary search
Return the index of target in a sorted list, or -1 if not present.
Quicksort
Implement quicksort and return a sorted list.
BFS level-order traversal
Return the level-order traversal of a binary tree as a list of lists.
Coin change (DP)
Find the minimum number of coins to make exactly the target amount.
LRU cache decorator
Implement @lru_cache(maxsize=N) for unary functions using OrderedDict.
Graph DFS
Return all nodes reachable from a start node via DFS.
Longest increasing subsequence
Return the length of the longest strictly increasing subsequence.
Topological sort (Kahn)
Return a valid topological ordering of tasks, or [] if a cycle exists.
Word ladder length
Return the length of the shortest transformation from beginWord to endWord changing one letter at a time.
Index of peak element
Implement a function that returns the index of any peak element in a given integer array.
Count inversions lite
Implement a function that counts inversions in a list of numbers efficiently.
Count pairs with given difference
Count how many unordered pairs in a list have a given absolute difference using an efficient approach.
Find Peak Element
Implement a function that returns the index of any peak element in an integer array.
Previous Smaller Element
Find the nearest previous index with a smaller value for every element in an array.
Longest Consecutive Sequence
Given an unsorted list of integers, find the length of the longest consecutive elements sequence in O(n) time.
Median of Two Sorted Arrays
Given two sorted arrays, return the median of the combined sorted array in O(log(min(n,m))) time.
Pascal Triangle Row
Given a non-negative integer n, return the nth row of Pascal's triangle as a list of integers.
Employee Hierarchy
Build an employee hierarchy tree and compute the total number of direct and indirect reports for each employee.
Union Find Class
Implement a UnionFind class with find and union operations supporting path compression and union by size.
Bubble Sort
Implement bubble sort that sorts a list of numbers in ascending order.
Selection Sort Implementation
Implement selection sort to sort a list of numbers in ascending order.
Merge Sort
Implement merge_sort(numbers) that returns a sorted copy of the input list using the merge sort algorithm.
Heap Sort Implementation
Implement the heap sort algorithm to sort a list of comparable elements in non-decreasing order.
Radix Sort
Implement LSD radix sort to sort a list of non-negative integers in ascending order.
Bucket Sort
Implement bucket sort to sort a list of floating-point numbers in the range [0,1).
Shell Sort
Implement Shell sort, an in-place comparison sort that generalizes insertion sort, using a gap sequence that shrinks by half each pass.
Exponential Search
Implement exponential search to find any valid index of a target in a sorted list.
Decode Ways
Count the number of ways to decode a numeric string into letters using the mapping A=1 to Z=26.
Path Sum II All Paths
Return all root-to-leaf paths where the sum of node values equals a target.
Redundant Connection
Given a list of edges forming a tree plus one extra edge, return the edge that appears last in the input and creates a cycle.
Reconstruct Itinerary
Given a list of airline tickets, reconstruct the itinerary in order using each ticket exactly once, choosing the lexicographically smallest path when multiple options exist.
Shortest Path in Binary Matrix
Implement BFS to find the shortest path length from (0,0) to (n-1,n-1) in an n x n binary matrix, moving through 0 cells in 8 directions.
Context manager timer
Implement a Timer context manager that records elapsed seconds.
Infinite counter generator
Create an infinite counter starting from `start`, stepping by `step`.
Retry decorator
Implement @retry(times=3) that retries a function on exception.
2D Vector dataclass
Implement a Vector2D dataclass with +, -, scalar *, dot product, and magnitude.
Data pipeline
Implement a Pipeline class supporting pipe chaining with the | operator.
Validated descriptor
Implement a TypedField descriptor that raises TypeError if the value is not of the expected type.
Async Context Manager Lifecycle
Build an async context manager class that tracks acquisition and ensures cleanup.
Custom iterator class
Implement a custom iterator class that repeatedly yields elements from a list up to a given number of times.
Generator Pipeline
Implement a generator function that yields only even numbers from an input list, squared.
Range-like generator
Implement a custom generator that yields numbers like Python's range but with flexible bounds.
Fibonacci Generator
Create a generator function that yields Fibonacci numbers from 0 upward until a given limit.
Prime Sieve Generator
Implement a generator function that yields prime numbers from 2 up to a specified limit, using an efficient sieve approach.
Window Iterator
Implement a generator that yields consecutive windows of a given size from any iterable.
Pairwise Sequence Pairs
Write a generator function pairwise that yields each consecutive overlapping pair from any iterable as lists.
Groupby Consecutive
Write a generator function that yields (value, list_of_occurrences) for each run of consecutive equal items.
Collatz Generator
Implement a generator function that yields the Collatz sequence starting from a given positive integer.
Digit Expansion Generator
Create a generator that lazily yields each decimal digit of a non-negative integer from most significant to least significant.
File Line Reader Generator
Implement a generator function that reads a file-like object and yields each non-empty line without loading the whole file into memory.
Tree inorder generator
Write a generator function that yields a binary tree's node values in inorder traversal.
Yield from delegation
Implement a generator that flattens nested iterables of any depth using `yield from`.
Once Decorator: Run a Function Only Once
Implement a decorator that caches and returns the result of the first call for subsequent calls.
Timing Decorator
Implement a decorator that prints the execution time of a function.
Memoize with TTL
Implement a decorator that caches function results for a limited time, returning cached values within the TTL and recomputing after expiry.
LRU Memoize
Implement an LRU memoization decorator that caches results for a fixed number of arguments.
Context Manager Class
Implement a context manager class that measures execution time and sets duration, with None if an exception occurred.
Cached Property Manual
Implement a decorator that turns a method into a lazy cached attribute per instance.
Rate Limit Decorator
Implement a decorator that enforces a maximum number of calls per second for any function.
Cache result decorator
Create a decorator that stores results of function calls keyed by positional arguments.
Profile time decorator
Create a decorator that tracks how many times a function is called and its cumulative execution time.
Print Args Decorator
Write a decorator that prints function name and arguments, then returns the original result.
File Open Context Manager
Create a class that acts as a context manager for opening a virtual file in memory.
Temporary directory manager
Implement a context manager that creates a temporary directory and automatically removes it even on errors.
Timer Context Manager
Implement a context manager that measures execution time of a with block and stores it.
Suppress stderr manager
Implement a context manager that suppresses all output written to stderr during its block.
Context Decorator Dual
Implement a timing decorator and a context manager that both record elapsed time in seconds.
Safe Integer from String
Implement safe_int that converts a string to an integer, returning a default value on any failure, with support for an optional base.
Safe divide function
Implement safe_divide that returns None on ZeroDivisionError and TypeError.
Safe int parser
Implement safe_parse_int that converts a string to an int, returning a default value on failure.
Safe Float Parser
Write a function that safely converts a string to a float, returning None for invalid inputs.
Divide with zero check
Write a function that safely divides two numbers, catching division by zero.
Key error handler
Implement a safe dictionary access function that returns a default value on missing keys.
Else on try block
Implement a function that uses try-except-else to safely divide two numbers and return a result or error description.
Validate Email Regex
Implement a function that validates email addresses using regex with specific rules.
Validate phone number
Write a function that uses regular expressions to determine if a given string is a valid US phone number.
Match IPv4 Address
Write a function that uses a regular expression to check if a string is a valid IPv4 address.
Match IPv6 Address
Write a function that uses a regex to validate whether a string is a fully expanded IPv6 address.
Match Credit Card Pattern
Write a function that validates a credit card number string against a set of formatting rules.
Validate Hex Color Code
Write a function that validates hex color codes using regular expressions.
Multiline anchor match
Extract lines beginning with a plain-text prefix from multiline strings using Python's re module.
Lookahead Validation
Write a regex-based function to check if a password meets length and character class requirements.
Nth Triangular Number
Implement a function that returns the nth triangular number efficiently.
Clamp and round to nearest ten
Clamp a number between given bounds and round the result to the nearest ten with halves away from zero.
Integer Square Root Floor
Implement a function that returns the greatest integer whose square is ≤ n, using only integer operations.
Power set size
Compute the size of the power set of a given sequence.
Polynomial evaluator
Implement a polynomial evaluator that computes the value of a polynomial given as a list of coefficients.
Catalan number
Implement a function that returns the nth Catalan number using dynamic programming.
Stirling number
Implement a function to compute Stirling numbers of the second kind S(n,k).
Euler Totient Function
Implement Euler's totient function φ(n) for positive integers.
Sieve of Eratosthenes
Implement the Sieve of Eratosthenes to return a sorted list of all primes up to a given integer n.
Prime Factorization
Return a sorted list of prime factors of a positive integer, including repeated factors.
Count divisors
Compute the number of positive divisors of a given integer using its prime factorization.
Sum of divisors
Given an integer n, return the sum of all its positive divisors.
Perfect Number Check
Write a function that returns True if a number is perfect, i.e., equal to the sum of its proper divisors.
Abundant Number Check
Implement a function to check whether a given integer is abundant: sum of proper divisors exceeds the number.
Amicable Numbers Check
Write a function that checks if two numbers are an amicable pair by comparing sums of proper divisors.
Armstrong Number Check
Implement a function that checks if a given integer is an Armstrong number.
Happy number check
Implement a function that returns True if a number is happy, False otherwise.
Harshad Number Check
Write a function that checks if a number is a Harshad (or Niven) number.
Smith Number Check
Write a function to check if a number is a Smith number by comparing digit sums of the number and its prime factorization.
Triangular Number
Implement a function that returns the nth triangular number using the closed-form formula.
Pentagonal Number
Given a positive integer n, return the nth pentagonal number using the formula P(n) = n(3n - 1)/2.
Lucas Sequence
Implement a function to compute the n-th Lucas number using iteration or recursion with memoization.
Partition function
Write a function that returns the number of ways to write a positive integer as a sum of positive integers (order irrelevant).
Multiply without multiply
Write a function that multiplies two integers using only addition, subtraction, and bit shifts — no * operator.
Count Set Bits
Implement a function that returns the number of set bits (1s) in the binary representation of a non-negative integer.
Check Power of Two Bits
Implement is_power_of_two(n) that returns True if n is a power of two and False otherwise.
Single Number XOR
Given a non-empty list of integers where every element appears twice except one, return the single number using XOR.
Missing Number XOR
Given a list of n distinct numbers from 0 to n with one missing, use XOR to find and return the missing number.
Gray Code Encode
Implement a function that converts a non-negative integer to its Gray code representation using bitwise XOR and shift.
Gray Code Decode
Implement gray_decode(n) that converts an n-bit Gray code integer back to its standard binary value using XOR accumulation.
Find Rightmost Set Bit
Implement a function that returns the 1-indexed position of the rightmost set bit of a positive integer, or 0 if none.
Isolate Rightmost Set Bit
Given an integer, return a number with only its rightmost set bit set.
Rotate Bits Left
Implement a function that rotates the bits of an integer to the left by a specified number of positions.
Bitwise AND of a Range
Given a range [a, b], return the bitwise AND of all integers in that inclusive range without iterating over all numbers.
Add without plus
Implement a function that adds two integers using only bitwise operations, no arithmetic plus or minus.
Divide using shifts
Implement division of two integers using only bit shifts and arithmetic, without using division or modulo operators.
Bit Mask Permissions
Implement helper functions to compose bit masks and check permission bits using bitwise operators.
Set kth Bit
Implement a function that sets the kth bit (0-indexed) of a non-negative integer to 1 and returns the result.
Clear kth Bit
Implement a function that clears the k-th bit of a non-negative integer (turns it to 0) using bitwise operations.
Compress Bits Run
Write a function that compresses a binary string by representing consecutive identical bits as a count-bit pair.
Sparse Number Check
Check if a non-negative integer is sparse, meaning its binary representation contains no adjacent 1 bits.
Brian Kernighan count
Implement a function that counts set bits using Brian Kernighan's efficient algorithm.
Levenshtein Distance
Implement the classic Levenshtein distance algorithm to measure string similarity.
Kadane Variant: Maximum Product Subarray
Implement max_product_subarray(nums) that returns the maximum product of any contiguous subarray.
Max Profit from Selling Twice
Compute the maximum profit that can be achieved by completing at most two buy-sell transactions on a given price array.
Bell number
Implement a function to compute the Bell number B(n) using dynamic programming.
Climbing Stairs
Implement a function that returns the number of distinct ways to climb n stairs using steps of 1 or 2.
Min cost climbing stairs
Compute the minimum total cost to reach the top of a staircase, given you can climb 1 or 2 steps at a time.
House Robber
Given a list of house values, return the maximum sum you can rob without robbing two adjacent houses.
House Robber Circular
Solve the House Robber problem with houses arranged in a circle.
Unique Paths in a Grid
Count the number of unique paths from the top-left corner to the bottom-right corner of a grid, moving only right and down.
Unique Paths with Obstacles
Given a 2D grid with obstacles, count the unique paths from top-left to bottom-right moving only down or right.
Triangle Minimum Path
Compute the minimum path sum from top to bottom of a triangle given as a list of lists.
Maximal square
Given a 2D binary matrix of 0s and 1s, compute the area of the largest square containing only 1s.
Longest Common Subsequence
Given two strings, compute the length of the longest subsequence common to both.
Longest Palindromic Subsequence
Compute the length of the longest palindromic subsequence in a given string.
Edit Distance (Levenshtein Distance)
Implement the classic edit distance algorithm to find the minimum number of single-character edits required to transform one string into another.
0/1 Knapsack
Implement the classic 0/1 Knapsack dynamic programming solution to maximize value under a weight capacity.
Unbounded Knapsack
Given item weights and values with unlimited copies, find the maximum total value that fits in a knapsack capacity.
Partition Equal Subset
Determine whether a given list of positive integers can be partitioned into two subsets with equal sum.
Target Sum Subsets
Write a function that counts the number of subsets of a list of positive integers that sum exactly to a target.
Coin Change Minimum
Given coin denominations and a target amount, compute the minimum number of coins needed or -1 if impossible.
Coin Change Ways
Count the number of distinct combinations of coins that sum to a target amount.
Perfect Squares Sum
Given a positive integer n, return the least number of perfect squares (e.g., 1, 4, 9, 16, ...) that sum to n.
Integer Break Product
Given a positive integer n, break it into at least two positive integers that sum to n and maximize their product.
Word Break DP
Implement a function to check if a string can be segmented into space-separated dictionary words.
Palindrome Partitioning Minimum Cuts
Given a string, return the minimum number of cuts needed such that every substring in the partition is a palindrome.
Egg Drop Puzzle
Given k eggs and n floors, compute the minimum number of attempts required in the worst case to find the highest safe floor.
Paint House Colors
Given a cost matrix, compute the minimum total cost to paint all houses with no two adjacent houses having the same color.
Buy Sell Stock with Cooldown (DP)
Given daily stock prices, compute the maximum profit you can achieve if you must wait one day after selling before buying again.
Longest Arithmetic Subsequence
Given a list of integers, return the length of the longest arithmetic subsequence (constant difference) within it.
Binary Search Tree Class
Build a BinarySearchTree class and a sequence runner that executes a list of operations.
Binary Tree Inorder Traversal
Implement an inorder traversal function that returns node values in left-root-right order.
Preorder Traversal
Implement a function that returns the preorder traversal values of a binary tree.
Postorder Traversal
Implement a function that returns the postorder traversal of a binary tree as a list of node values.
Maximum depth of tree
Implement max_depth(root) to return the maximum depth of a binary tree.
Minimum Depth of Tree
Given a binary tree, compute the minimum depth from the root to the nearest leaf node.
Symmetric Tree Check
Write a function that checks whether a binary tree is symmetric (a mirror of itself).
Same Tree Check
Write a function that checks whether two binary trees are identical in structure and node values.
Lowest Common Ancestor in a Binary Tree
Implement a function to find the lowest common ancestor (LCA) of two nodes in a binary tree.
Sum Root to Leaf Numbers
Given the root of a binary tree, compute the total sum of all root-to-leaf numbers.
Binary tree left side view
Given a binary tree, return the leftmost node's value at each depth, from top to bottom.
Vertical Order Traversal
Compute the vertical order traversal of a binary tree, grouping nodes by column and row.
Delete Node in BST
Implement a function that deletes a key from a binary search tree and returns the new root.
Insert into BST
Implement insertion into a Binary Search Tree while maintaining BST properties.
Trim BST to range
Implement a function to trim a BST to only retain nodes with values in a given inclusive range.
Dijkstra Shortest Path
Implement Dijkstra's algorithm on a weighted graph to return distances from a source to every node.
Bellman-Ford Algorithm
Implement the Bellman-Ford algorithm to compute shortest distances from a source in a directed weighted graph with up to 100 vertices and negative edges.
A* Pathfinding Heuristic
Implement A* search on a 2D grid to find the shortest path length between two cells.
Cycle Detection in a Directed Graph
Use DFS with a recursion stack to detect cycles in a directed graph.
Cycle Detection in Undirected Graph
Write a function that detects if an undirected graph contains a cycle.
Articulation Points
Implement a function that returns the articulation points of an undirected graph.
Bridges in Graph
Implement a function that returns all bridges in an undirected graph.
Hamiltonian Path Check
Implement a function that checks whether an undirected graph has a Hamiltonian path using DFS and backtracking.
Minimum Cut
Given an undirected graph in adjacency-list form, return the size of the minimum edge cut that disconnects the graph.
Bipartite Graph Check
Implement a function to check if an undirected graph is bipartite using graph coloring.
Graph Coloring
Given an undirected graph, determine if it can be colored with two colors such that adjacent vertices have different colors.
Course Schedule Can Finish
Given numCourses and prerequisites, return whether all courses can be finished without cyclic dependencies.
Alien Dictionary Order
Given a sorted list of words in an alien language, derive the order of its unique letters.
Graph Valid Tree
Determine if n nodes and an edge list form a valid tree (connected and acyclic).
All Paths from Source to Target
Given a directed acyclic graph, return all paths from node 0 to the last node.
Network Delay Time
Given a directed weighted graph and a starting node, find the minimum time for a signal to reach all nodes, or -1 if unreachable.
Cheapest Flights Within K Stops
Implement a function to compute the cheapest flight price from source to destination with at most K stops in a directed weighted graph.
Find the Town Judge
Given n people and a trust array, return the town judge or -1.
Find center of star graph
Write a function that finds the center node of a star graph from its list of edges in O(1) time.
Keys and Rooms
A classic graph traversal challenge: check if all rooms are reachable from room 0 using keys found in visited rooms.
Wildcard Match (Simple)
Write a function that checks whether a string matches a pattern with '*' and '?' wildcards.
Permutation Generator
Write a function that returns all permutations of a list of distinct integers.
Combination Generator
Write a recursive function that returns all combinations of length k from a list of distinct integers.
Stock Buy Sell Once
Given daily stock prices, compute the maximum profit you can achieve from buying once and selling once later.
Search in Rotated Array
Implement an efficient search in a rotated sorted array using modified binary search.
Interpolation Search
Implement interpolation search in Python on a sorted list of integers.
Ternary Search
Implement ternary search to locate the maximum of a discrete unimodal function.
Container With Most Water
Given an array of heights, find the maximum area between two vertical lines that can hold water.
Trapping Rain Water
Given an array of non-negative integers representing an elevation map, compute how much water it can trap after raining.
Best Time to Buy and Sell Stock
Given a list of daily stock prices, determine the maximum profit achievable by buying on one day and selling on a later day.
Sort Colors (Dutch National Flag)
Implement the Dutch National Flag algorithm to sort an array of 0, 1, 2 in one pass.
Longest Substring Without Repeating Characters
Implement a function that returns the length of the longest substring without repeating characters.
Minimum Window Substring
Implement a sliding window algorithm to find the minimum window substring containing all characters of a given pattern.
Character Replacement Window
Given a string and a number k, find the length of the longest substring that can be made uniform by replacing at most k characters.
Permutation in String
Determine if any permutation of a shorter string appears as a contiguous substring in a longer string using an efficient sliding window.
Count Nice Subarrays
Given an array of integers, count the number of contiguous subarrays that contain exactly k odd numbers.
Subarrays with K different ints
Count the number of contiguous subarrays that contain exactly K distinct integers.
Balanced brackets in string
Check if a string of brackets is properly balanced using a stack-based approach.
Next Greater Element
Return a list where each position holds the next greater element to the right, or -1 if none exists.
Min Heap Class
Build a MinHeap class with push, pop, peek, and size methods that maintain a valid min-heap.
Top K Frequent Elements
Given an integer array and a number k, return the k most frequent elements using a heap-based approach.
Spiral Matrix Order
Given a 2D matrix, return all elements in clockwise spiral order starting from the top-left.
Valid Sudoku Board
Determine if a 9x9 Sudoku board is valid by checking rows, columns, and 3x3 sub-boxes.
Number of Islands
Given a 2D grid of '1' (land) and '0' (water), count the number of islands surrounded by water.
Max Area of Island
Given a 2D grid of 0s and 1s, find the maximum area of a connected group of 1s.
01 Matrix Nearest Zero
Given a binary matrix, return a matrix of the same shape where each cell contains the Manhattan distance to the nearest 0.
Rotting Oranges Time
Given a grid of fresh, rotten, and empty cells, compute the minimum minutes until all fresh oranges rot, or -1 if some are unreachable.
Days in month
Write a function that returns the number of days in a given month and year, correctly handling leap years.
Extract JSON-like numbers
Parse a simplified JSON-like string without using the json module and sum all numbers found in it.
Showing 467 challenges
Guide: free Python coding challenges
Practice Python by solving problems
PythonSkillset challenges are hands-on coding exercises from beginner to advanced. Open a challenge, read the problem, write Python in the split-pane editor, and run tests with Pyodide — no install required.
How to use the arena
- Pick a category — basics, algorithms, strings, and more
- Open a challenge, read the statement, and edit the starter code
- Run tests, fix failures, then try a related quiz or tutorial lesson
Challenges vs tutorials and quizzes
Challenges test what you can build under constraints. For guided teaching, use our Python tutorials. For quick checks, try quizzes or copy snippets from code samples.