Python ยท Real Python

Algorithms in Python: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1Big-OEasyMust Do

Measure how four functions grow as the input grows.

Q2Linear SearchEasy

Search a list one item at a time, and count the comparisons.

Q3Binary SearchEasyMust Do

Search a sorted list by halving the range each time.

Q4bisectEasyMust Do

Use the standard library's binary search.

Q5Bubble SortEasy

Write bubble sort and count what it costs.

Q6Selection SortEasy

Repeatedly select the smallest remaining item.

Q7Insertion SortEasy

Build the sorted result one item at a time.

Q8sorted() & TimsortEasyMust Do

Use Python's own sort, and see what it does that yours does not.

Q9RecursionEasyMust Do

Write your first recursive functions, and see the call stack.

Q10FibonacciEasy

Compute Fibonacci three ways and compare the cost.

Q11HashingEasyMust Do

Use a dictionary or set to replace a scan.

Q12Frequency CountingEasy

Count things in one pass.

Q13Two PointersEasyMust Do

Walk a list from both ends at once.

Q14Sliding WindowEasy

Find the best window of a fixed size without recomputing it.

Q15Prefix SumsEasy

Answer many range-sum questions with one pass of setup.

Q16StacksEasy

Use a list as a stack, and solve a classic with it.

Q17Queues & dequeEasy

Use the right structure for first-in, first-out.

Q18HeapsEasy

Keep the smallest item always to hand.

Q19Merge SortEasy

Sort by splitting, sorting each half, and merging.

Q20Quick SortEasy

Sort by partitioning around a pivot.

Q21Counting SortEasy

Sort without comparing, when the values are small integers.

Q22MatricesEasy

Work with a grid of rows and columns.

Q23String AlgorithmsEasy

Solve the classic string problems.

Q24Number AlgorithmsEasy

Solve the classic number problems.

Q25Choosing an ApproachEasyMust Do

Solve one problem five ways and compare.

Q26Binary Search VariantsMediumMust Do

Find the first and last occurrence of a value, not just any one.

Q27Rotated ArraysMedium

Search a sorted list that has been rotated.

Q28Binary Search on the AnswerMedium

Binary search over a range of possible answers, not over a list.

Q29In-Place Two PointersMedium

Rearrange a list in place with a read pointer and a write pointer.

Q30Three SumMedium

Find triples that sum to a target, without a triple loop.

Q31Variable Sliding WindowMediumMust Do

Grow and shrink a window to find the best one.

Q32Windows with CountsMedium

Match a window against a required set of counts.

Q33Prefix Sums & HashingMediumMust Do

Count subarrays with a given sum in one pass.

Q34Kadane's AlgorithmMedium

Find the best contiguous run in one pass.

Q35Grouping & Top-KMedium

Group by a computed key and rank the results.

Q36Set AlgorithmsMedium

Solve problems with set operations instead of loops.

Q37Sorting to UnlockMedium

Sort first, and the problem becomes easy.

Q38Merging IntervalsMediumMust Do

Merge, insert and subtract overlapping ranges.

Q39Index as HashMedium

Use the list's own indices as a lookup table.

Q40Recursive EnumerationMedium

Generate every subset and every permutation.

Q41BacktrackingMedium

Search a space of choices, undoing each one that fails.

Q42MemoisationMediumMust Do

Turn an exponential recursion into a linear one.

Q43Dynamic ProgrammingMedium

Fill a table when each answer depends on smaller ones.

Q44GraphsMedium

Represent a graph and explore it.

Q45Breadth-First SearchMediumMust Do

Explore level by level, and find the shortest path.

Q46Depth-First SearchMedium

Explore as deep as possible, and use it to find components and cycles.

Q47Weighted Shortest PathMedium

Find the cheapest route when edges have different costs.

Q48Union-FindMedium

Track groups that merge, and answer "are these connected?" instantly.

Q49Greedy AlgorithmsMedium

Take the locally best choice, and know when that is enough.

Q50Choosing a TechniqueMedium

Recognise which technique a problem wants.

Q51Log AnalysisMediumMust Do

Answer real questions about a large log with the right structure for each.

Q52AutocompleteMedium

Suggest completions for a prefix, three ways.

Q53DeduplicationMediumMust Do

Find near-duplicates, not just exact ones.

Q54SchedulingMedium

Schedule jobs to meet deadlines and minimise waiting.

Q55RecommendationMedium

Recommend items from what similar users liked.

Q56Route PlanningMedium

Plan a journey with changes, costs and constraints.

Q57Text IndexingMediumMust Do

Build a search index over documents.

Q58CachingMedium

Implement an LRU cache and measure the hit rate.

Q59Load BalancingMedium

Distribute work across servers, and see what each strategy costs.

Q60Version DiffingMedium

Compare two sequences and report the changes.

Q61CompressionMedium

Build a Huffman code and measure the saving.

Q62Spell CheckingMedium

Suggest corrections for a misspelled word.

Q63Rate LimitingMedium

Implement three rate limiters and compare their behaviour.

Q64Pagination & RankingMediumMust Do

Page through ranked results without re-sorting everything.

Q65Grid ProblemsMedium

Solve the classic grid questions with flood fill and BFS.

Q66StreamingMedium

Process data that does not fit in memory.

Q67MatchingMedium

Match two sides of a market with preferences.

Q68Anomaly DetectionMedium

Spot unusual values in a series.

Q69EncodingMedium

Encode and decode data with bit-level tricks.

Q70BenchmarkingMediumMust Do

Measure properly before deciding anything.

Q71DebuggingHardMust Do

This "fast" duplicate check is slower than the naive one. Explain and fix it.

def has_duplicate(values):
    seen = []
    for value in values:
        if value in seen:
            return True
        seen.append(value)
    return False
 
print(has_duplicate(list(range(30000))))
Q72Hidden CostsHard

Find the operations that cost more than they look.

Q73Recursion LimitsHardMust Do

Hit Python's recursion limit, and work around it.

Q74Mutable Memo KeysHard

A cache that silently returns the wrong answer.

Q75Sorting TrapsHard

Sorting that quietly does the wrong thing.

Q76Worst CasesHard

Find the input that makes a good algorithm behave badly.

Q77Space ComplexityHard

Count memory, not just time.

Q78Floating PointHard

Numeric results that are subtly wrong.

Q79Early ExitHard

Stop as soon as the answer is known.

Q80Premature OptimisationHardMust Do

Optimise the wrong thing, then find the real cost.

Q81Off-by-OneHard

The index bugs that hide in loops and slices.

Q82Wrong StructureHard

The same algorithm, ruined by the wrong container.

Q83Correctness Under Edge CasesHard

The inputs that break an otherwise correct algorithm.

Q84RandomnessHard

Randomised algorithms, and how to test them.

Q85Reading ComplexityHard

Work out the complexity of code you did not write.

Q86Mini-ProjectMini-ProjectMust Do

Build a Search Engine with an index, ranking and suggestions.

Q87Mini-ProjectMini-Project

Build a Route Planner with a map, costs and constraints.

Q88Mini-ProjectMini-Project

Build a Recommendation Engine with several strategies.

Q89Mini-ProjectMini-Project

Build a Timetable Scheduler with constraints and backtracking.

Q90Mini-ProjectMini-Project

Build a Data Pipeline that streams, transforms and aggregates.

Q91Mini-ProjectMini-Project

Build a Puzzle Solver for Sudoku with constraint propagation.

Q92Mini-ProjectMini-ProjectMust Do

Build a Text Analysis toolkit with several algorithms.

Q93Mini-ProjectMini-Project

Build a Warehouse Optimiser with packing, picking and routing.

Q94Mini-ProjectMini-Project

Build an Algorithm Visualiser that traces execution step by step.

Q95Mini-ProjectMini-Project

Build an Algorithm Benchmark Suite that measures growth.

Q96InterviewInterview

Analyse the complexity of every operation you use, and justify the numbers.

Q97InterviewInterview

Given a problem, choose an approach and defend it.

Q98InterviewInterview

Explain when to write an algorithm and when to call the standard library.

Q99InterviewInterview

Take a slow function through a full optimisation pass.

Q100CapstoneInterviewMust Do

Build an Algorithms Workbench โ€” the complete demonstration of this topic. Solve one realistic problem end to end, choosing a technique at each stage, and prove every choice with measurements.

Still stuck on something?

Book a free 1-on-1 session and we'll work through it together.

Book a Free Session