Factorial (iterative)
Compute n! iteratively without recursion.
Clamp a Number to a Range
Implement a clamp function that returns a value within a specified range.
Max of a variable-length list
Implement a function that returns the maximum value from a list of numbers without using max().
Replace negatives with zero
Implement a function that replaces all negative numbers in a list with zero.
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.
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.
Modulo Remainder
Implement a function that returns the remainder of a divided by b without using the modulo operator.
Digit Count
Count the number of digits in an integer using arithmetic, without string conversion.
Find Missing Number
Given a list of n distinct integers from 0..n with one missing, return the missing number.
Enumerate with start
Implement a function that mimics Python's enumerate with a custom start index.
Convolve 1D signal
Implement a 1D convolution function with three modes using pure Python.
Guess Number Game
Simulate a number guessing game with attempts, feedback, and a win/lose result.
Longest Substring with K Repeating Characters
Return the length of the longest substring of a given string in which every character appears at least K times.
Basic Calculator
Implement a function that evaluates a simple arithmetic expression with +, -, *, / and parentheses.
Broadcast Add Scalar
Add a scalar to every number in a 2D list and return a new 2D list without modifying the original.
Reshape array dimensions
Implement a function that reshapes a 1D list into a 2D list with given dimensions.
Title case converter
Return the string with each word capitalised.
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.
Normalize quotes
Replace all typographic quote characters with straight ASCII quotes.
Interleave Two Strings
Given two strings s1 and s2, return a new string that interleaves them character by character, starting with s1.
Center a string in a width
Write a function that centers a string within a specified width by adding spaces on both sides.
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.
Replace Spaces with Dashes
Write a function that replaces every space in a string with a dash.
Compress Consecutive Chars
Write a function that compresses a string by replacing runs of identical characters with the character followed by the count.
Index of First Occurrence
Implement a function that finds the starting index of a substring within a string, returning -1 when absent.
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.
Extract domain from URL
Extract the domain (hostname without port or www) from a given URL string.
Basic Calculator III
Implement a recursive descent parser to evaluate a fully parenthesized arithmetic expression with +, -, *, / and parentheses.
Minimum Remove Valid Parentheses
Given a string with parentheses and letters, remove the fewest parentheses to make it valid.
Parse URL components
Write parse_url that splits a URL into its standard components with defaults for missing parts.
Parse key-value lines
Parse structured key-value lines into a dictionary with support for quoted values and escaped characters.
Decode base64 string
Write a function that decodes a base64 string to its original UTF-8 text without using the base64 module.
User Friendly Message
Given a raw user input, format it into a single clean sentence with proper sentence case and trimming.
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.
Remove duplicates (sorted)
Return a sorted list with duplicates removed.
Product except self
Return an array where output[i] is the product of all elements except nums[i], without using division.
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.
Pad Array Edges
Write a function that pads a list with zeros on both ends.
Sort array by parity
Given a list of integers, return a new list with all evens first and odds last, preserving original relative order.
Linear Interpolation Array
Given an array with some None values, replace them by linear interpolation between the nearest known values.
Are two lists the same multiset
Write a function that checks if two lists contain the same elements with the same multiplicities, ignoring order.
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.
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.
Top k keys by count
Given a dictionary mapping keys to counts, return the top k keys with the highest counts, breaking ties alphabetically.
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.
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.
Count Pairs with Sum
Implement a function that counts the number of distinct pairs in a list summing to a target.
Group by Department
Implement a function that groups a list of employee dictionaries by department, returning a dictionary keyed by department with lists of employee dictionaries.
Pivot sales by product
Write a function that pivots sales records into a dictionary keyed by product with monthly totals.
Stack class
Implement a Stack class with push, pop, peek, is_empty, and size.
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.
Queue class (list-based)
Implement a Queue class with enqueue, dequeue, peek, is_empty, and is_full methods using a list.
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.
Design Twitter Feed
Implement a Twitter class with postTweet, getNewsFeed, follow, and unfollow methods.
Deck of Cards Class
Implement a Deck class representing a standard 52-card deck with shuffle, deal, and len support.
Dataclass with slots
Implement a slotted frozen dataclass representing a 2D point with total ordering.
Playing card class
Design a PlayingCard class with suit, rank, color, and equality/comparison magic methods.
Count pairs with given difference
Count how many unordered pairs in a list have a given absolute difference using an efficient approach.
Previous Smaller Element
Find the nearest previous index with a smaller value for every element in an array.
Union Find Class
Implement a UnionFind class with find and union operations supporting path compression and union by size.
Basic Calculator II
Evaluate a basic arithmetic expression with +, -, *, / following operator precedence.
Online Stock Span
Implement StockSpanner.next(price) that returns the maximum number of consecutive days (including today) with price <= current price.
Delete Old Records
Filter a list of records by removing those with a date older than a given cutoff date.
Argsort Indices
Implement a function that returns the indices that would sort a list of integers, with ties broken by original order.
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.
Default Argument Trap
Implement a function that safely accumulates items without the classic mutable default argument bug.
TypeVar bounded generic
Learn to use TypeVar with bounds to write type-safe generic functions in Python.
Context Variable Scope
Implement a context manager that temporarily changes a global variable and restores it afterwards, even if an exception occurs.
Range-like generator
Implement a custom generator that yields numbers like Python's range but with flexible bounds.
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.
Cartesian Product Generator
Implement a generator function that yields the Cartesian product of multiple input iterables without precomputing all results.
Zip Longest Fill
Create an iterator that yields lists from multiple iterables, padding with a fill value when lengths differ.
Graph DFS Generator
Implement a generator function that performs a depth-first traversal of a graph without recursion.
Memoize with TTL
Implement a decorator that caches function results for a limited time, returning cached values within the TTL and recomputing after expiry.
Context Manager Class
Implement a context manager class that measures execution time and sets duration, with None if an exception occurred.
Timer Context Manager
Implement a context manager that measures execution time of a with block and stores it.
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.
Divide with zero check
Write a function that safely divides two numbers, catching division by zero.
Validate Email Regex
Implement a function that validates email addresses using regex with specific rules.
Multiline anchor match
Extract lines beginning with a plain-text prefix from multiline strings using Python's re module.
Match Balanced Parentheses with Regex
Write a function that uses regular expressions to determine if parentheses are balanced and properly nested.
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.
Lucas Sequence
Implement a function to compute the n-th Lucas number using iteration or recursion with memoization.
Multiply without multiply
Write a function that multiplies two integers using only addition, subtraction, and bit shifts — no * operator.
Chinese Remainder Theorem
Solve a system of congruences with pairwise coprime moduli using the Chinese Remainder Theorem.
Stars and Bars Count
Implement stars_and_bars_count(n, k) which returns the number of ways to put n identical items into k distinct bins, with bins allowed to be empty.
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.
Isolate Rightmost Set Bit
Given an integer, return a number with only its rightmost set bit set.
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.
Clear Rightmost Set Bit
Write a function clear_rightmost_set_bit that accepts a non-negative integer and returns the integer with its rightmost set bit cleared.
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 with Obstacles
Given a 2D grid with obstacles, count the unique paths from top-left to bottom-right moving only down or right.
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.
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.
Cherry Pickup Maximum
Given a grid with cherries, find the maximum cherries you can collect using two paths from top-left to bottom-right.
Count subsets with sum
Given a list of integers and a target sum, count how many subsets of the list sum to the target.
Trim BST to range
Implement a function to trim a BST to only retain nodes with values in a given inclusive range.
Range Sum BST
Return the sum of all node values in a BST that lie within a given inclusive range [low, high].
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.
Cycle Detection in a Directed Graph
Use DFS with a recursion stack to detect cycles in a directed graph.
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.
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.
Swim in Rising Water
Find the minimum time needed to swim from the top-left to the bottom-right of a grid where water level rises and you can only move to cells with elevation ≤ current time.
Possible bipartition
Given N people and a list of mutual dislikes, check if they can be divided into two groups with no dislike inside a group.
Android unlock patterns
Count the number of valid Android unlock patterns of a given length using a 3x3 grid with adjacency constraints.
Floyd-Warshall: All-Pairs Shortest Paths
Implement the Floyd-Warshall algorithm to find all-pairs shortest path distances in a directed graph with possibly negative weights but no negative cycles.
Wildcard Match (Simple)
Write a function that checks whether a string matches a pattern with '*' and '?' wildcards.
Word Search Backtrack
Determine if a given word exists in a 2D board by tracing adjacent cells without reusing any cell.
Remove invalid parentheses
Given a string with parentheses and letters, return all valid strings after removing the minimum number of invalid parentheses.
Partition Equal Subset Sum (Backtracking)
Write a function that uses backtracking to decide if a list of positive integers can be partitioned into two subsets with equal sum.
Candy Distribution
Compute the minimum total candies needed so that every child gets at least one and children with higher ratings than neighbors get more candies.
Remove K Digits to Form the Smallest Number
Given a non-negative integer as a string, remove exactly k digits to form the smallest possible integer without leading zeros.
Maximize units on truck
Given box types with count and units per box, maximize total units loaded onto a truck.
Bag of Tokens Score
Given tokens with values and initial power, determine the maximum score achievable by selling tokens for power or buying tokens for score.
Job Sequencing with Deadlines and Profits
Given jobs with deadlines and profits, choose a subset that maximizes profit while meeting deadline constraints.
Max events attended
Given a list of events with start and end times, find the maximum number of non-overlapping events you can attend.
Koko Eating Bananas
Given piles of bananas and hours, find the minimum integer eating speed Koko needs to finish all piles within H hours.
Capacity to Ship Packages
Given package weights and days allowed, compute the smallest ship capacity that can deliver all packages in order within the given days.
Maximum Running Time of n Computers
Use binary search to maximize the running time for n computers with batteries.
Rotated Array Search II
Implement a function to search for a target in a rotated sorted array with possible duplicates.
Search 2D Matrix
Given a sorted 2D matrix with sorted rows and first element of each row greater than last of previous, find target efficiently.
Container With Most Water
Given an array of heights, find the maximum area between two vertical lines that can hold water.
Longest Substring Without Repeating Characters
Implement a function that returns the length of the longest substring without repeating characters.
Subarrays with K different ints
Count the number of contiguous subarrays that contain exactly K distinct integers.
Minimum Size Subarray Sum
Given an array of positive integers, return the minimal length of a contiguous subarray with sum at least target, or 0 if none exists.
Fruit into Baskets
Given an array of integers representing fruit types, return the maximum number of fruits you can collect in a contiguous subarray with at most two distinct types.
Binary Subarray with Sum
Given a binary list and a goal sum, count the number of subarrays that add up to that goal.
Longest Substring with At Most K Distinct Characters
Given a string and an integer k, find the length of the longest substring that contains at most k distinct characters.
Container With Most Water
Compute the maximum area between two vertical lines in an array of heights.
Max Stack Design
Implement a MaxStack class with push, pop, top, and get_max operations.
Decode String Stack
Decode a compressed string with repeated substrings like '3[a2[c]]' to 'accaccacc' using a stack-based approach.
Buildings with ocean view
Given building heights, return sorted indices of buildings that have a clear view of the ocean to their right.
Asteroid Collision
Simulate asteroid collisions with a stack and return the remaining asteroids in original order.
Decode Nested String
Implement a function that decodes a string with nested encoding patterns.
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 a list of integers and a number k, return the k most frequent elements in descending order of frequency, with ties broken by larger value.
Task Scheduler Heap
Given a list of tasks and a cooldown, find the minimum number of CPU intervals needed to schedule all tasks without violating the cooldown.
Find K pairs with smallest sums
Given two sorted arrays and an integer k, return the k smallest pairs (u, v) with the smallest sums, sorted by sum.
Meeting Rooms II with Heaps
Given a list of meeting intervals, compute the minimum number of rooms required using a heap-based approach.
Minimum Cost to Connect Sticks
Compute the minimum total cost to connect all sticks into one stick by repeatedly combining two sticks with the smallest lengths.
Count square submatrices with all ones
Count all square submatrices consisting entirely of 1s in a binary matrix.
Largest Plus Sign
Compute the largest possible plus sign of 1s in an n x n grid with some cells set to 0.
Word Search Matrix
Given a 2D board and a word, determine if the word can be formed by sequentially adjacent cells (horizontally or vertically), without reusing cells.
Age in years months days
Given birth and reference dates, return age as a dictionary with years, months, days.
Week Number ISO
Given a date, return its ISO 8601 week number (1–53) without using datetime.isocalendar().
Extract JSON-like numbers
Parse a simplified JSON-like string without using the json module and sum all numbers found in it.
Generate CSV row
Implement a function that converts a list of values into a single CSV row with correct quoting and escaping.
Parse YAML-like dict
Parse a simple YAML-like text with indentation into a nested dictionary.
Flatten nested JSON
Write a function that flattens nested JSON objects into a flat dictionary with dot-separated keys, handling lists and empty objects.
Unflatten JSON dict
Given a flat dictionary with keys like 'a.b.c', reconstruct the nested dictionary where each dotted segment becomes a nested level.
Encode Base64 String
Write a function that encodes a UTF-8 string into a base64 string without using the base64 module.
Serialize dict to TOML-like
Convert nested Python dicts into a simplified TOML-like string with sorted keys, type-aware formatting, and flat table sections.
Create Table Schema
Write a function that creates a SQLite table with a given name and columns, and returns the resulting schema as a list of column definitions.
Customers Never Order
Given Customers and Orders tables, return the names of customers with no orders, sorted alphabetically, or None if all have ordered.
Constant Time Compare
Write a function that compares two strings without leaking length or content via timing.
Password Salt Hash
Implement a function that returns a secure salted SHA-256 password hash with a deterministic format.
XOR Cipher Encode
Implement the XOR cipher: encode a string by XORing each character with a key character.
Showing 174 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.