Browse every C# and system design kata
598 katas across 8 tracks, and 225 of them are free to solve. Open one to read its brief, then write and grade your solution in the browser.
Showing all 598 katas
No katas match.
Algorithm 130
C# coding challenges →- Add Binary Strings Easy Free 10 min Add two binary numbers far too long for any built-in integer.
- Base64 Decoded Length Easy Free 8 min The decoded size is pure arithmetic - no need to decode.
- Batched Binary Search Easy Free 10 min Answer twenty thousand membership queries against a sorted array.
- Best Time to Buy and Sell Stock Easy Free 10 min Maximize the profit from a single buy followed by a later sell.
- Climbing Stairs Easy Free 10 min Count the ways up a staircase taking one or two steps at a time.
- Contains Duplicate Easy Free 8 min Decide whether an array contains any repeated value.
- Count Distinct Letters Easy Free 8 min How many different letters appear? A 26-slot array already knows.
- Count Missing Sample Runs Easy Free 15 min Count every contiguous interval with no recorded sample, even when the timeline is too large to expand.
- Count Pairs With Difference K Easy Free 10 min Count the pairs of indices whose values differ by exactly k.
- Count Words Easy Free 8 min Count words by spotting boundaries, not by splitting.
- Counting Bits Easy Free 10 min Popcounts for 0..n - reuse the table you are already building.
- Excel Column Number Easy Free 8 min Spreadsheet columns are base-26 with no zero digit.
- Find Pivot Index Easy Free 10 min The index where everything to the left weighs the same as everything to the right.
- Flood Fill Easy Free 10 min The paint-bucket tool - including the click that changes nothing.
- GCD of an Array Easy Free 8 min The greatest common divisor of many numbers - Euclid, not trial division.
- Happy Number Easy Free 10 min Does repeatedly summing squared digits reach 1 - and how do you KNOW it will not?
- House Robber Easy Free 10 min Maximize the loot without robbing two adjacent houses.
- Integer Square Root Easy Free 10 min Floor of the square root, found without floating point.
- Island Perimeter Easy Free 10 min Walk the coastline of the island - in both directions.
- Isomorphic Strings Easy Free 10 min Can one string be turned into the other by a consistent character substitution?
- Kth Missing Positive Number Easy Free 10 min Find the k-th positive integer the sorted array skipped.
- Longest Rising Streak Easy Free 10 min Measure a consecutive telemetry climb without rescanning every possible starting point.
- Majority Element Easy Free 10 min Find the element that appears more than half the time.
- Max Sum Subarray of Size K Easy Free 10 min The biggest sum any window of exactly k elements can reach.
- Maximum Bracket Depth Easy Free 8 min How deep do the parentheses nest? A counter beats a stack.
- Merge Sorted Arrays Easy Free 10 min Merge two sorted arrays into one - without destroying what makes them special.
- Min Cost Climbing Stairs Easy Free 10 min Pay each step you land on; reach the top as cheaply as possible.
- Missing Number Easy Free 8 min Which value from 0..n is absent? Arithmetic answers in one pass.
- Move Zeroes Easy Free 10 min Push all zeros to the end while keeping the other values in order.
- Parse and Sum Integers Easy Free 10 min Sum space-separated integers (negatives included) allocation-free.
- Power of Two Easy Free 8 min One bit trick, two edge cases waiting to bite.
- Release the Buffered Packets Easy Free 15 min Report how far an ordered stream can advance as packets arrive late, out of order, or more than once.
- Remove All Adjacent Duplicates Easy Free 10 min Keep deleting adjacent equal pairs until none remain.
- Remove Duplicates From Sorted Array Easy Free 10 min Deduplicate a sorted array without forgetting that it is sorted.
- Reverse Bits Easy Free 10 min Reverse a 32-bit pattern - signed shifts will betray you.
- Roll Back the Payload Ledger Easy Free 15 min Track staged payload totals while nested checkpoints are opened and rolled back.
- Roman to Integer Easy Free 10 min Read Roman numerals, subtractive pairs included.
- Run-Length Decoded Length Easy Free 8 min How long would the decoded string be? Do not decode it to find out.
- Single Number Easy Free 8 min One value appears an odd number of times - XOR finds it for free.
- String Compression Easy Free 10 min Run-length encode a string without quadratic string building.
- Sum of Digits Easy Free 10 min Sum every digit of every number, without allocating along the way.
- Sum of Unique Elements Easy Free 8 min Sum the values that appear exactly once in the array.
- The Loss Listed Above the Gains Easy Free 7 min The treasury report put a ¥2.1B loss on top of the gains at month end, and every earlier close looks fine. What did October do differently?
- Three Extra Ledger Entries Easy Free 7 min Big payout runs reach the bank with three rows too many, and always the same three. Find out why before the next run settles.
- Trimmed Sum Easy Free 8 min Sum everything except one min and one max - without sorting a copy.
- Two Amounts of Tax on One Line Easy Free 6 min A customer rejected an invoice whose only line disagrees with its own total by a cent. How does one number come out as two?
- Two Sum Easy Free 10 min Find the indices of the two numbers that add up to a target.
- Two Sum II (Sorted Input) Easy Free 10 min Two Sum again - but the array is sorted, and that changes everything.
- Unique Paths Easy Free 10 min Count the robot's lattice paths across the grid.
- Valid Anagram Easy Free 10 min Decide whether two strings are anagrams of each other.
- Valid Palindrome Easy Free 10 min Is the sentence a palindrome once punctuation and case are ignored?
- Valid Parentheses Easy Free 10 min Are the brackets balanced and properly nested?
- 3Sum (Sorted Output) Medium Free 25 min Find all distinct triplets that sum to zero, in sorted order.
- Boats to Save People Medium Free 20 min Pair people into two-person boats under a weight limit, using as few boats as possible.
- Coin Change (Fewest Coins) Medium Free 25 min The fewest coins that make the amount, or -1.
- Coin Change II (Count the Ways) Medium Free 20 min How many coin combinations make the amount?
- Compare Version Numbers Medium Free 15 min Compare dotted version strings numerically, not textually.
- Container With Most Water Medium Free 20 min Pick two lines that, with the x-axis, hold the most water.
- Contiguous Array Medium Free 20 min Longest subarray holding as many zeros as ones.
- Count Quadruples Summing to Target Medium Free 20 min Count index quadruples that sum to a target - without the quadruple loop.
- Count Substring Occurrences Medium Free 15 min Count overlapping occurrences by comparing characters, not slicing strings.
- Course Schedule Medium Free 20 min Can every course be finished, or do the prerequisites form a cycle?
- Cutting Ribbons Medium Free 20 min The longest equal piece length that still yields k pieces.
- Daily Temperatures Medium Free 20 min For each day, how long until a warmer one?
- Decode String Medium Free 20 min Expand k[encoded] patterns, nesting included.
- Decode Ways Medium Free 20 min How many letter strings could this digit string encode?
- Degree of an Array Medium Free 20 min Find the shortest contiguous slice whose most-frequent-element count matches the whole array.
- Evaluate Reverse Polish Notation Medium Free 15 min Evaluate a postfix expression - and get integer division right.
- Find All Anagram Start Indices Medium Free 20 min Every position where an anagram of the pattern begins.
- Find the Duplicate Number Medium Free 25 min Find the one repeated value in an array of n+1 numbers from 1..n, without allocating a set to do it.
- Fruit Into Baskets Medium Free 20 min Longest stretch of trees using at most two fruit types.
- Gray Code at an Index Medium Free 15 min The n-th Gray code without generating the first n-1.
- Hex Checksum Medium Free 15 min Sum the bytes of a hex string with nibble arithmetic, not substrings.
- House Robber II (Circular Street) Medium Free 20 min The street is a circle now - the first and last houses are neighbors.
- How Many Sensor Rings Fit? Medium Free 30 min Count nonnegative sensor readings consistent with adjacent sums around a ring, without trying every possible first reading.
- Integer to Roman Medium Free 15 min Write Roman numerals the way Romans did - greedily.
- Koko Eating Bananas Medium Free 20 min The slowest eating speed that still finishes every pile in time.
- Longest Consecutive Sequence Medium Free 20 min Find the length of the longest run of consecutive integers hiding in an unsorted array.
- Longest Increasing Subsequence Medium Free 25 min Length of the longest strictly increasing subsequence - faster than the quadratic DP.
- Longest Palindromic Substring (Length) Medium Free 20 min How long is the longest palindrome hiding in the string?
- Longest Repeating Character Replacement Medium Free 20 min Longest uniform run you can create with k character replacements.
- Maximum Subarray Medium Free 20 min Find the largest sum of any contiguous subarray.
- Minimum Days to Make Bouquets Medium Free 20 min Earliest day enough adjacent flowers have bloomed for all the bouquets.
- Minimum Forward Jumps Medium Free 25 min Cross a jump array with the fewest hops, including dead ends, without enumerating every reachable edge.
- Minimum Size Subarray Sum Medium Free 20 min The shortest window of positive numbers reaching a target sum.
- Minimum Travel Pass Cost Medium Free 25 min Cover sparse travel dates with overlapping pass durations while paying for no unnecessary calendar state.
- Modular Exponentiation Medium Free 15 min Raise to a power of 10^18 - one squaring at a time.
- Most Common Word Length Medium Free 15 min Which word length appears most often? Count lengths, not words.
- Multiply Numeric Strings Medium Free 25 min Schoolbook multiplication of numbers thousands of digits long.
- Number of Islands Medium Free 20 min Count the connected patches of land in a grid.
- One Sale, Two Business Days Medium Free 10 min During a terminal rollout, the same moment in the same shop landed on two different business days, and evening takings started drifting into tomorrow.
- Partition Equal Subset Sum Medium Free 25 min Can the array split into two halves of equal sum?
- Partition Labels Medium Free 20 min Cut a string into the most pieces so no letter spans two pieces.
- Product of Array Except Self Medium Free 20 min For each index, return the product of all other elements, without division.
- Reconnect the Stations Medium Free 30 min Find the first connection event that reunites every station without rebuilding reachability after each cable.
- Reminders for Collected Parcels Medium Free 10 min Customers keep getting nightly reminders for parcels they collected days ago. Trace the failed pickup through the locker logs and fix it.
- Rotting Oranges Medium Free 20 min How many minutes until the rot spreads everywhere?
- Ship Packages Within D Days Medium Free 20 min Smallest ship capacity that delivers the conveyor belt on schedule.
- Shortest Path in Binary Matrix Medium Free 20 min Shortest 8-directional path across an open grid - DFS wanders, BFS knows.
- Simplify Unix Path Medium Free 20 min Canonicalize a Unix path - and survive the .. that climbs past root.
- Smallest Repeating Upload Medium Free 30 min Find the shortest chunk that reproduces a whole upload, including cases where a long overlap ends mid-copy.
- Sort Colors Medium Free 20 min Sort an array of 0s, 1s and 2s in a single pass.
- String to Integer (atoi) Medium Free 20 min Parse a messy numeric prefix with correct clamping at the int limits.
- Subarray Sum Equals K Medium Free 20 min Count contiguous subarrays whose elements sum to a target k.
- Subarrays Divisible by K Medium Free 20 min Count the subarrays whose sum is divisible by k.
- Sum of Absolute Differences Medium Free 20 min For each element of a sorted array, the total distance to all the others.
- Sum of All Subarray Sums Medium Free 15 min Add up the sum of every contiguous subarray - without enumerating them.
- The Outage at 0% Errors Medium Free 8 min A route failed for 40 minutes while the dashboard showed 0% errors, so the alert never fired. Where did 412 failed requests go?
- Toggle Inspection Ranges Medium Free 30 min Count the slots left on after overlapping range toggles when the board is too large to visit slot by slot.
- Top K Frequent Elements Medium Free 20 min Return the k most frequent values, most frequent first.
- Ways to Make a Fair Array Medium Free 20 min Count the removals that leave odd and even index sums equal.
- Word Break Medium Free 20 min Can the string be segmented into dictionary words?
- Zigzag Conversion Medium Free 15 min Write the string in a zigzag over n rows, then read row by row.
- Count Bounded Range Sums Hard Free 40 min Count signed subarray totals inside an inclusive band without enumerating quadratic pairs.
- Count Inversions Hard Free 35 min Count every out-of-order pair without examining every pair.
- Edit Distance Hard Free 35 min Fewest single-character edits turning one word into another.
- Fewest Cache Fetches Hard Free 45 min Use tomorrow's requests to find the smallest possible number of cache misses today.
- First Missing Positive Hard Free 30 min Find the smallest positive integer that does not appear in the array.
- Largest Rectangle in Histogram Hard Free 35 min The biggest rectangle that fits under the bars.
- Last Patch Wins Hard Free 45 min Recover the final contents of a strip after a long log of overlapping range assignments.
- Longest Cycle in a Functional Graph Hard Free 40 min Find the largest directed cycle without retracing every path.
- Longest Well-Performing Interval Hard Free 30 min Longest stretch of days with more tiring days than easy ones.
- Magnetic Force Between Two Balls Hard Free 35 min Place m balls in baskets to maximize the smallest gap between any two.
- Minimum Window Substring (Length) Hard Free 35 min Length of the shortest window of text covering every required character.
- Route With a Waiver Hard Free 45 min Spend one assisted crossing to make a route's hardest remaining step as small as possible.
- Shortest Subarray With Sum at Least K Hard Free 45 min Find the shortest target-reaching interval when negative values break the usual window.
- Sum of Subarray Minimums Hard Free 35 min Add the minimum of every contiguous subarray - by counting, not enumerating.
- Text Justification Hard Free 40 min Greedily pack words into fully justified lines, spaces and all.
- Trapping Rain Water Hard Free 30 min Compute how much rain water is trapped between bars of an elevation map.
- Weighted Reservation Schedule Hard Free 40 min Choose a maximum-value set of nonoverlapping reservations with a mandatory cleanup gap.
EF Core and SQL 206
EF Core practice →- Absent, Null, or Empty? Easy Pro 12 min Distinguish a missing JSON key, explicit JSON null, an empty string, and every other value before grouping the audit.
- Add It Up in SQL Easy Pro 10 min Join two tables and return one aggregated number with SUM, read back as a scalar.
- Bird Sightings by Species Prefix Easy Pro 12 min If a type-ahead over 240,000 sightings still hauls back a twenty-sixth of the table, the index is in the plan and doing none of the work.
- Books by Genre or Language Easy Pro 12 min An OR is only as indexable as its weakest branch.
- Builds by Result Easy Pro 10 min An index covers one expression, not one column.
- Cars by Make and Color Easy Pro 12 min Why does a planner that happily intersects two indexes settle for one of them here? The statistics are fresh, so the answer is in the WHERE clause.
- Cities Connected Both Ways Easy Pro 10 min Find unordered pairs with a self-join: an inequality predicate keeps one orientation where DISTINCT cannot.
- Count Check-ins for a Member Easy Pro 10 min A gym profile card's visit count drags every turnstile swipe back over the wire.
- Counting Conversations Easy Pro 10 min Count distinct agent-customer pairs when the report's concatenated string key silently collides.
- Dishes per Cuisine Easy Pro 8 min Count how many dishes sit in each cuisine with one grouped query.
- Distinct Ate My Ordering Easy Pro 12 min Distinct throws away an ordering applied before it. Collapse the duplicates first, then order what is left.
- Do Not Wrap the Indexed Column Easy Pro 10 min A function on an indexed column (lower(), upper()) disables the index. Compare the column directly.
- Domain Names by Prefix Easy Pro 12 min The registrar's prefix index is built exactly right for this search, and the planner still refuses it.
- Emails by Folder or Label Easy Pro 12 min The AND search on this mailbox screen answers in a millisecond. The OR search beside it, written by the same hand, reads all three hundred thousand messages.
- Everybody Looked New Easy Pro 12 min "Never ordered before" is a fact about a customer's whole history, not about any one order, which is why the acquisition report has never removed a returning customer.
- Existence Without Loading Easy Free 10 min Answer a yes/no existence question by asking the database, not by loading the rows to count them.
- Fans of Both Franchises Easy Pro 12 min Buyers of both product lines, not either: prove two separate purchase facts about the same customer.
- Filter Before or After the Fold Easy Pro 10 min A row predicate parked in HAVING sums every tier into the bar; WHERE runs before the fold and HAVING after.
- Filter Before You Fetch Easy Free 8 min Filter measurements on the database, not after loading the whole table.
- Has a Plate Been Seen Easy Pro 10 min Ask the database for existence so it stops at the first indexed hit instead of reading every row.
- Invoices by Number Easy Pro 10 min Support pastes in nine invoice numbers. Finding them reads sixty thousand rows today, and two hundred thousand next year.
- Items by Brand and Category Easy Pro 12 min A marketplace filter fetches fifteen hundred listings to return a hundred, because only one of its two indexes ever made it into the plan.
- Join Two Tables Easy Pro 10 min Write a SQL JOIN to follow a foreign key and pull columns from a related table.
- Latest Messages in a Channel Easy Pro 10 min One composite index can serve a filter and a sort at once: no separate sort step.
- Let the Index Serve ORDER BY + LIMIT Easy Pro 10 min Take the newest N rows server-side so an index on the sort column returns them without scanning the table.
- Line Items in a Tab Easy Pro 8 min Count one tab's line items by asking the database for the number, not by loading the rows.
- Merge the Feeds, Keep the Truth Easy Pro 10 min UNION deduplicates and UNION ALL does not: merge two event feeds without losing real duplicate events.
- One Line per Team Easy Pro 10 min Aggregate input order is unspecified: give string_agg its own ORDER BY inside the call, and order the lines outside.
- Posts in a Thread Easy Pro 10 min Two years after the thread page shipped, the index built for it still reports zero scans.
- Project Only the Names Easy Free 8 min Select just the customer names server-side instead of materializing whole entities to read one column.
- The Conversion Rate That Exploded Easy Pro 12 min Safe division: stop a zero denominator from raising without deleting the row that carries it.
- The Cutoff That Moved Easy Pro 15 min Half of a composed report still reads the wall clock, so its window has nothing to do with the window the other half measured from the report's anchor.
- The Unrated Rose to the Top Easy Pro 12 min Where empty values land in an ORDER BY is decided by the direction you sorted, so a descending worst-first list opens with the rows nobody has rated.
- Total Revenue in a Country Easy Pro 8 min Sum the order totals for one country with a single translated query instead of loading every row.
- Trim the Rows, Then Fold Easy Pro 10 min A group-level count counts every row that reached the group. Filter the rows before you fold them.
- Vehicle Pings in a Month Easy Pro 10 min A composite index answers from its leading column inward, or it does not answer at all.
- Whole Cases Without Overflow Easy Pro 12 min Project case counts and unused capacity with integer quotient and remainder, without overflowing near the largest line quantity.
- Your First SELECT Easy Free 8 min Write a raw SQL query with Dapper: filter rows with WHERE and sort with ORDER BY.
- A Group for Every Reading Medium Pro 25 min EF Core will not put a C# banding rule in a GROUP BY, and grouping by the raw reading instead buys a group per row. Give the provider a key it can work out itself.
- A Line Is Not a Unit Medium Pro 20 min Compute category unit prices with quantity-weighted server-side aggregates.
- A Local Month over a UTC Column Medium Pro 25 min The report wants a local month, the column stores UTC. Convert the bounds; converting the column costs the index.
- A Marginal Rate Is Not a Flat Rate Medium Pro 15 min Join income across every crossed band and sum the taxable slice in each progressive bracket.
- A Reading Has an Expiry Medium Pro 20 min Carry the latest non-null sample to a report grid only while that sample remains fresh.
- A Tile for Every Genre Medium Pro 25 min A LINQ inner join renders only the genres that sold; drive the browse page from the catalogue so every advertised genre keeps its tile.
- Accounts With Clean Books Medium Pro 20 min Combine a nonempty guard with universal quantification, so every order must reconcile without loading the account graph.
- Average Basket Size Medium Pro 20 min Average number of line items per tab, computed server-side.
- Average Measurement Value per Device Medium Pro 15 min Compute each device's average measurement value in one query, not an N+1 loop.
- Average Rates Lie Medium Pro 15 min Compose campaign KPIs from summed numerators and denominators instead of averaging unequal daily rates.
- Booking Total vs Line Sum Medium Pro 20 min Audit bookings whose stored total disagrees with their line items, comparing both in one translated query.
- Comments on a Post Medium Pro 15 min The filter runs in C#, so Postgres reads every comment.
- Compare It to Everyone but Itself Medium Pro 15 min Build a centered peer average with an explicit window exclusion so the current transaction cannot hide its own anomaly.
- Continue After This Order Medium Pro 20 min Turn a timestamp and id cursor into a fully ordered seek predicate, so a deep page reads only the rows it returns.
- Count Active Devices Medium Pro 15 min Collapse a per-device existence probe into one server-side count under a memory cap.
- Count Applications by Status Medium Pro 15 min The SQL is hand written, so nothing was mistranslated. It still reads every application so C# can do the narrowing.
- Counting Only What Counts Medium Pro 20 min Fold booking counts, premium counts and premium revenue per region out of one grouped query with conditional aggregates.
- Customer Order Totals Medium Free 15 min Sum each customer's orders with a single SQL query instead of an N+1 loop.
- Customers Without Orders Medium Free 15 min Find customers who never ordered with one anti-join instead of an N+1 loop.
- Detail, Subtotal, Grand Total Medium Pro 20 min Build several aggregation grains in one scan and distinguish stored NULLs from subtotal placeholders with GROUPING.
- Discard One Extreme at Each End Medium Pro 20 min Compute a one-sample trimmed mean per sensor without dropping every tied minimum or maximum.
- Either Segment, Once Medium Pro 20 min Combine two customer segments with queryable Union so overlapping members appear once and only the final set is returned.
- Every Order at the Latest Instant Medium Pro 20 min Find each customer's latest order timestamp without throwing away other orders tied at that same instant.
- Every Product Gets a Sales Row Medium Pro 20 min Use a LINQ left outer join so unsold products remain in a grouped sales report.
- Every Required Certification Medium Pro 20 min Match all required certifications with PostgreSQL array containment and a selective GIN index.
- Find Me Anything Tagged Both Medium Pro 20 min Array containment answers "carries all of these tags", overlap answers "carries any of them". Use each for its own question.
- GROUP BY and HAVING Medium Pro 15 min Group rows, count per group, and filter the groups with HAVING in raw SQL.
- Here, But Never There Medium Pro 15 min Use queryable Except to find products sold in one market and absent from another without materializing either market set.
- How Long Until the Next One Medium Pro 20 min Report the days until each patient's next visit with a forward-looking window function, and keep the visit that has no follow-up yet.
- Include Only the Open Ones Medium Pro 25 min A collections screen lists each account's open orders and keeps the accounts that have none: filter the child collection you load, not the parents you keep.
- Is a Username Taken Medium Pro 15 min A signup availability check that reads every account to answer one yes/no question.
- Is Spend Still Moving Conversion? Medium Pro 15 min Measure campaign direction and strength with PostgreSQL regression aggregates while handling degenerate samples.
- Issues for a Repo Medium Pro 20 min The repo slug never leaves your process, so Postgres is asked for two whole tables and obliges.
- Items Sold Below List Price Medium Pro 15 min Find the line items whose unit price undercuts the show's list price with one translated comparison, not a client-side scan.
- Latest Sensor Events Medium Pro 15 min Return the newest few events without paying for the whole event log.
- Latest Tickets for an Agent Medium Pro 20 min One agent's newest tickets, found by dragging six hundred agents' worth of rows into memory first.
- Loyalty Means Separate Orders Medium Pro 15 min Find customer-product pairs repeated across distinct orders without confusing duplicate lines for loyalty.
- Match the Duplicate Units Medium Pro 15 min Reconcile duplicate receipt units with INTERSECT ALL instead of collapsing them to a set.
- Median Order per Country Medium Pro 20 min Filter country groups by their median order total, which AVG cannot give you.
- Nothing Vanishes Twice Medium Pro 20 min Chain two method-syntax left joins without losing customers or line-less orders.
- One Contact per Email Medium Pro 20 min Keep one canonical row per duplicate group with ROW_NUMBER over a priority ordering, not GROUP BY aggregates.
- One Month After the Thirty-First Medium Pro 25 min Add whole months from the original anchor date so month-end clamping happens once instead of compounding.
- Optional Filters Stay Composable Medium Pro 20 min Conditionally add nullable search filters to an IQueryable so EF executes only the final composed order query.
- Parcels by Tracking Id Medium Pro 15 min Resolve a batch of tracking numbers without dragging the parcels table into memory.
- Podium with Ties Medium Pro 20 min Rank tied athletes the olympic way: shared places, a skipped next place, and a podium that is not just the top three rows.
- Posts for a Blog Medium Pro 20 min The slug lives in one table and the posts in another, and neither index is ever handed a value to seek on.
- Products Both Markets Buy Medium Pro 15 min Compose two product-id queries with Intersect so Postgres returns the overlap in one statement instead of two market-sized lists.
- Rank a Release Before It Ships Medium Pro 20 min Use a hypothetical-set RANK aggregate to place an unpersisted release in every channel leaderboard.
- Region Revenue Ranking Medium Pro 15 min Rank regions by amount rental revenue in one translated query, not by grouping in memory.
- Repeat Customers Medium Pro 15 min Find customers with more than one order using a single query instead of an N+1 loop.
- Revenue by Genre Medium Pro 15 min Revenue per title genre from rental lines, in one grouped query.
- Risk Bands That Do Not Split Ties Medium Pro 15 min Assign percentile risk bands with CUME_DIST so accounts with equal scores remain together.
- Seventeen-Minute Buckets Medium Pro 15 min Align meter readings to fixed seventeen-minute buckets relative to a caller-supplied origin with date_bin.
- Subscribers Who Never Clicked Medium Pro 20 min Find rows with no match using a NULL-safe anti-join; one NULL makes NOT IN return nothing.
- Ten Rows Is Not the Top Ten Medium Pro 20 min The widget owes ten best sellers plus everyone level with the tenth, and LIMIT counts rows, not sales figures.
- The Aisle That Went On Sale Medium Pro 25 min Two zones of one page want two prices for the same product, but inside a context that row is one object, so the campaign price lands on the grid's tiles too.
- The Average That Threw Medium Pro 15 min AVG over an empty segment is SQL NULL, and EF throws reading it back into a decimal. Aggregate so an empty segment comes home as zero.
- The Branches That Disappeared Medium Pro 25 min Every branch must appear, zeros included: a month filter in WHERE silently turns a LEFT JOIN into an INNER JOIN.
- The Empty Bucket Still Exists Medium Pro 20 min Build a complete numeric histogram with width_bucket, exact boundaries, and explicit underflow and overflow bins.
- The Filter That Came Home Medium Pro 25 min A C# helper called inside
Whereis a wall EF Core cannot see through, so the rule runs at home over the whole table. Hand the provider a rule it can still read. - The Group Key Is a Customer Medium Pro 20 min Translate an order summary grouped by its related customer entity.
- The ID List Belongs in the Query Medium Pro 20 min Translate a local product-id collection into a server-side set predicate instead of filtering a materialized category.
- The Index Speaks the Same Collation Medium Pro 15 min Apply an explicit case-insensitive, accent-sensitive collation that matches the product-name index instead of normalizing every row.
- The Index That Only Covers the Unsent Medium Pro 25 min Postgres reaches for a partial index only when the query's own WHERE clause proves the index's WHERE clause.
- The Index Was on the Function All Along Medium Pro 20 min An index built ON lower(email) serves only predicates that name that same expression.
- The Invoice That Was Off by Four Cents Medium Pro 20 min Money arithmetic has an order: round every line to cents first, then add, because one ROUND after the SUM quietly drops a fraction of a cent per line.
- The Join That Multiplied the Total Medium Pro 25 min Joining a customer to their purchases and their refunds at once multiplies both totals. Fold each one over its own rows.
- The Last Calls of the Month Medium Pro 25 min The WHERE clause is already perfect and the plan still reads four thousand rows to hand back ten. Graded on the query plan.
- The Last Event Is Not This Event Medium Pro 15 min Annotate every session event with its true final event by giving LAST_VALUE the full partition frame.
- The Page That Kept Shifting Medium Pro 20 min Paging with Skip/Take over a sort key that has duplicates repeats some rows and hides others. Make the order total.
- The Playlist Position Is Data Medium Pro 15 min Expand an integer array with WITH ORDINALITY so playlist order and repeated tracks survive the join.
- The Running Total That Jumped Medium Pro 25 min A running balance over tied timestamps prints the same end-of-batch total on every line of the batch, because the default window frame folds rows that tie into one.
- The Second Purchase Is Per Customer Medium Pro 20 min Use a correlated bounded subquery to select each customer's second chronological order.
- The Support Board Cross-Tab Medium Pro 20 min Pivot row-per-status data into per-status columns with COUNT(*) FILTER, zeros included.
- The Sync That Lied Medium Pro 20 min Audit a drifted replica: <> against NULL is UNKNOWN, so the corrupted rows report as in sync.
- The Vanishing Respondents Medium Pro 20 min COUNT(*) vs COUNT(column): NULLs vanish from counts, averages, and filters, and take your response rate with them.
- The Whole Customer Roster Medium Pro 20 min Use .NET 10 RightJoin so dormant customers remain beside customers with orders.
- The Wildcard Is Part of the Name Medium Pro 20 min Escape user-supplied wildcard characters and use the three-argument EF Like function for a literal prefix search.
- Three Price Tiers of Depth Medium Pro 20 min Use a GROUPS window frame to measure rolling auction depth across distinct price tiers without splitting peers.
- Titles Above the Average Price Medium Pro 15 min List titles priced above the catalog average, letting the database compute the average and filter in one pass.
- Top Earner, No Windows Allowed Medium Pro 25 min Find every department's top earners, ties included, with a correlated NOT EXISTS or a department-aware join, never a window function.
- Top Spending Customers Medium Free 15 min Return the highest-spending customers with one ranked query, not an N+1.
- Touching Is Not Overlapping Medium Pro 20 min Find canonical conflict pairs with half-open timestamp ranges and calculate their true intersection.
- Two Consecutive Readings Confirm It Medium Pro 20 min Confirm alarms from adjacent high samples within a maximum gap, without skipping intervening low readings.
- Two Ledgers, One Truth Medium Pro 20 min Reconcile two ledgers with one FULL OUTER JOIN: keep rows from either side and COALESCE over the join keys.
- Two Trips for One Answer Medium Pro 25 min A
ToList()in the middle turns a composable query into plain values EF can only parameterize. Keep the intermediate query deferred so it nests as a subquery. - Two Warehouses, Matching Stock Medium Pro 25 min INTERSECT returns a set and throws duplicate rows away: count matched stock units with multiset semantics instead.
- Unsold Here Is Not Unsold Everywhere Medium Pro 20 min Keep the anti-join scoped to one market and compose it in SQL instead of carrying a large sold-id list between queries.
- Viewers Who Bought Both Medium Pro 15 min Find rows that satisfy two separate conditions at once with EXISTS or INTERSECT.
- When Everyone Can Attend Medium Pro 25 min Intersect every member’s multirange availability, treating unknown availability as unavailable, then clip and filter common windows.
- Who Bought This Show Medium Pro 20 min Find a show's ticket buyers in one statement instead of a query per booking.
- Who Stopped Listening Medium Pro 20 min Set difference between two time windows with EXCEPT: dedup semantics, positional columns, and a join back for the report row.
- Write Index-Friendly SQL Medium Pro 15 min Hand-written SQL, an indexed timestamp, and a month filter: the shape of your WHERE clause decides whether the planner can use the index.
- A Local Day Is Not Always 24 Hours Hard Pro 30 min Convert two local midnights to UTC so a sargable range survives daylight-saving transitions.
- Acquired, Then Returned Hard Pro 30 min Build a first-purchase cohort and preserve countries whose acquired customers never returned.
- Average by Time, Not Samples Hard Pro 35 min Reconstruct state intervals with the prior sample and LEAD, clip them to the report, and compute a duration-weighted average.
- Back After a Real Quiet Period Hard Pro 35 min Find immediate order gaps that create reactivation episodes and summarize them per customer.
- Balance at Every Order Hard Pro 30 min Project an inclusive running order balance with a deterministic correlated nested query.
- Basket Affinity with Method Joins Hard Pro 35 min Self-join order lines, canonicalize product pairs, and count supporting baskets exactly once.
- Bought Every Show in a Genre Hard Pro 25 min Relational division: find the rows that match every member of a set, not just one of them.
- Build a Cohort Retention Grid Hard Pro 35 min Anchor customers to their first purchase, then zero-fill a calendar-month retention grid.
- Build the Response in SQL Hard Pro 30 min Aggregate ordered child rows into stable JSON documents while preserving parents that have no children.
- Carving Sessions from the Clickstream Hard Pro 35 min Sessionize a clickstream with LAG gap detection and a running SUM, not clock-hour buckets.
- Choose the Auction Clearing Price Hard Pro 40 min Build cumulative demand and supply at every active limit price, then choose a clearing price with deterministic volume, imbalance, and reference-price priorities.
- Common Table Expressions Hard Pro 25 min Compare each country against the average of the country totals, an aggregate over aggregates.
- Customers Above Their Country Average Hard Pro 25 min Find customers whose total spend beats their country's average, in one query.
- Enforce an Ordered Conversion Funnel Hard Pro 35 min Carry each visitor's next valid timestamp through a campaign funnel without mixing or reordering events.
- Every Activity Survives the Merge Hard Pro 30 min Merge order and line facts with LINQ Concat, then aggregate the UNION ALL stream by customer and day.
- Every Anchor Buyer Also Bought This Hard Pro 30 min Use relational division to find products shared by every buyer of a dynamic anchor product.
- Every Cent Must Land Somewhere Hard Pro 30 min Use largest-remainder apportionment so rounded integer allocations conserve the exact budget.
- Everyone Under the CTO Hard Pro 25 min Walk a self-referencing org chart to any depth with WITH RECURSIVE and a depth counter.
- Explode the Bill of Materials Hard Pro 30 min Recursively multiply quantities along every BOM path and aggregate shared leaves without erasing duplicate requirements.
- Fetch the Request, Not Just the Set Hard Pro 30 min Turn requested composite keys into a parameterized VALUES table that preserves tenant scope, duplicates, and order.
- Follow the Money, Mind the Loop Hard Pro 30 min Walk a cyclic transfer graph with WITH RECURSIVE and a visited-path guard; without one the walk never terminates.
- Grants, Denials, and Sixty-Three Bits Hard Pro 25 min Combine role bitmasks with bitwise aggregates, apply deny precedence, and expand the effective permissions.
- How Concentrated Is Each Market? Hard Pro 30 min Compose customer and country aggregates to calculate a revenue concentration index.
- Latest Row per Group with DISTINCT ON Hard Pro 25 min Use Postgres DISTINCT ON to keep one row per group: the most recent order per customer.
- Let PostgreSQL Mark the Cycle Hard Pro 30 min Traverse dependency paths with declarative SEARCH ordering and CYCLE marking instead of a depth cap or hand-built visited guard.
- Longest Login Streak Hard Pro 30 min Gaps and islands: group consecutive days with the date minus ROW_NUMBER trick to find each player's longest streak.
- Market Rollup in Query Syntax Hard Pro 35 min Join four EF sets and fold monthly country-category facts into a compact market report.
- Markets That Appeared or Vanished Hard Pro 30 min Reconcile two monthly market aggregates with full-outer semantics in one EF query.
- Match Two Money Streams Hard Pro 35 min Allocate ordered payments across ordered invoices by intersecting their cumulative monetary spans.
- Month-over-Month Growth with LAG Hard Pro 25 min Compare each row to the one before it with LAG() over an ordered window of monthly totals.
- Nearest Depots Without Sorting the World Hard Pro 25 min Use PostgreSQL point distance ordering and a GiST KNN scan to find the nearest active depots.
- Never Touch the Table Hard Pro 30 min Ask only for what a covering index already carries so the plan becomes an index-only scan instead of a heap visit per row.
- Nobody Beats Them on Both Axes Hard Pro 30 min Find the customer skyline by anti-joining aggregated spend and order-count scores against every proper dominator.
- One Entitlement Must Satisfy Every Rule Hard Pro 35 min Use a GIN prefilter and parameterized JSONPath so product, scope, and enabled state match one object.
- One Order Total, However Many Lines Hard Pro 30 min Aggregate order and line measures at their own grains before joining country KPIs, preserving zero-activity markets without fanout.
- One Query per Row Hard Pro 30 min Collapse correlated SELECT-list subqueries into one grouped join: the N+1 that hides inside a single statement.
- One Query, One Parent Object Hard Pro 25 min Use Dapper multi-mapping and an identity map to assemble one parent object with an ordered child collection.
- One Query, Sixty Thousand Rows Hard Pro 30 min Chained collection Includes multiply into a cartesian row explosion. Ask the database for the answer instead of the graph.
- Page Six Thousand Hard Pro 35 min Deep pages must seek, not skip: serve a page from the cursor itself instead of walking the ledger to reach it.
- Peaks per Sensor, Not per Page Hard Pro 30 min Cut a group's rows down inside the IQueryable so EF emits a limit that restarts per sensor instead of one Take over the whole result.
- Rank Search Results, Do Not Scan Text Hard Pro 35 min Use a weighted stored tsvector, web-search syntax, coverage ranking, and a GIN index.
- Read an Index Like PostgreSQL Hard Pro 30 min Decode PostgreSQL index catalogs to preserve key order, expressions, sort options, and included columns.
- Recency, Frequency, and Money in One Fold Hard Pro 30 min Aggregate customer RFM metrics at an as-of date and apply deterministic segment precedence.
- Replay Bitemporal Prices Hard Pro 30 min Revalue historical sales using both business-valid time and the price history known at an earlier instant.
- Running Total with a Window Hard Pro 25 min Accumulate a running SUM with an ordered window, then find where it first crosses a line.
- Search One Audit Partition Hard Pro 30 min Keep a UTC month range on the partition key so PostgreSQL prunes eleven audit partitions.
- Seek Through the Leaderboard Hard Pro 30 min Apply a compound keyset cursor to grouped lifetime spend before sorting and limiting the customer leaderboard.
- Signals in the JSON Hard Pro 30 min Type jsonb fields before using them: ->> hands back text, and text compares and groups like text.
- Similar Buyers, Not Just Heavy Buyers Hard Pro 35 min Rank customer purchase sets by intersection-over-union similarity, so a large overlapping catalog does not automatically beat a close match.
- Slice of the Pie Hard Pro 25 min Give each region its percent of company-wide revenue in one pass with a window aggregate; integer division quietly zeroes every share.
- Subtract Busy Time with Multiranges Hard Pro 35 min Clip and merge overlapping appointments, subtract their multirange from a work shift, and return usable gaps.
- Support Is Not Lift Hard Pro 40 min Extend basket affinity with marginal counts, confidence in both directions, and lift.
- The Busiest Instant Hard Pro 35 min Find peak concurrency with a signed boundary sweep that respects half-open intervals and simultaneous handoffs.
- The Cells With No Sales Hard Pro 30 min Build a complete country-category matrix and preserve combinations with no matching sales.
- The Clock Stops After Five Hard Pro 35 min Intersect a ticket interval with timezone-aware working windows instead of subtracting weekends from wall-clock time.
- The CTE That Got Inlined Hard Pro 30 min A campaign report scores every listing with an expensive text match and joins the sales in, and the plan runs the scoring once per sales line instead of once per product.
- The Cutoff Includes Every Tie Hard Pro 30 min Select the top N distinct product-revenue scores in a subquery so every product tied at the cutoff survives.
- The Day That Started at Two in the Morning Hard Pro 35 min A timestamptz is an instant, not a wall clock: bucket UTC instants into the local calendar days a shop actually lives in, across a daylight saving change.
- The Join That Doubled the Money Hard Pro 30 min Aggregate independent child facts to invoice grain before joining them, or every payment multiplies every credit.
- The Months That Raised Nothing Hard Pro 30 min Report every month in a range, including the empty ones, with a generate_series calendar spine and a LEFT JOIN.
- The Most Specific Firewall Rule Wins Hard Pro 25 min Match IPv4 and IPv6 addresses with native network containment, then choose the longest enabled prefix.
- The Order Digest Tree Hard Pro 35 min Shape a bounded customer, order, and line-item tree inside one translated EF Core query instead of loading the full graph.
- The Order Immediately Before This One Hard Pro 30 min Correlate each order with its immediate predecessor through a translated lateral subquery.
- The Same Basket in Different Lines Hard Pro 35 min Compare order baskets as product-to-total-quantity multisets, independent of line splitting, prices, totals, and row order.
- The Seven-Day Window Hard Pro 30 min The default window frame is a cumulative average in disguise; a real per-store moving average needs an explicit frame and a partition.
- The Spill Changes the Next Step Hard Pro 35 min Replay ordered signed flows with a capacity clamp at every step, carrying discarded overflow and unmet withdrawals into a final audit.
- The Touch Must Precede This Conversion Hard Pro 30 min Attribute each conversion to its last eligible campaign touch using a conversion-relative window and deterministic tie break.
- The Whole Catalog, Not Just Several Products Hard Pro 30 min Use relational division to find customers who bought every product in a requested category.
- Three Latest Orders, Every Customer Hard Pro 30 min Take the top three rows per group with CROSS JOIN LATERAL, the index-friendly sibling of the window-function rank.
- Three Leaders in Every Market Hard Pro 30 min Take a bounded set of revenue leaders inside every country after a four-table aggregate.
- Top N per Group with a Window Function Hard Pro 25 min Use ROW_NUMBER() OVER (PARTITION BY ...) to rank within groups and take the top few.
- Totals, Subtotals, One Pass Hard Pro 30 min Detail rows, per-region subtotals and a grand total out of one pass over the table, with the rolled-up NULLs told apart from the ones the data already carries.
- Turn a Manifest into Rows Hard Pro 30 min Relationalize nested shipment packages with JSON_TABLE, typed defaults, and independent ordinality at each level.
- Who Owns the Category Hard Pro 30 min Join product revenue to an aggregate-of-aggregate denominator and filter by market share.
- Whose Basket Is a Proper Subset? Hard Pro 35 min Compare dynamic distinct purchase sets with nested existence checks and return every proper customer-set containment relation.
System Design Studio 78
System Design Studio →- Accept Notification Requests Easy Pro 20 min A campaign tool writes delivery rows from the browser and broken template references explode at send time. Put a Notification API in charge that resolves every template at intake.
- Admit Through a Waiting Room Easy Pro 25 min Someone pasted the checkout link into a group chat and 80,000 fans skipped the line. Keep checkout standing at 10:00.
- Bind Artifacts to Build Evidence Easy Pro 25 min A build script invents its own provenance. Move evidence creation into the trusted control plane and bind source and output digests.
- Build a Video Catalog Easy Pro 20 min Metadata in a database, video bytes in object storage, and one API owning both: the split every video platform starts with.
- Establish a Chat Session Easy Pro 20 min A prototype lets mobile clients write messages straight to storage. Introduce a trusted real-time gateway and chat service before scaling connections.
- Own the Checkout Command Easy Pro 20 min A storefront writes browser-priced orders straight to the database, and someone just bought a television for a cent. Put a Checkout API in charge, repricing every cart from the Product Catalog.
- Publish the First Post Easy Free with account 20 min A social prototype writes posts from the browser and hides follows in a JSON column. Put a trusted Post API in charge, with content in the Post Store and relationships in their own Social Graph.
- Restore Beside Live Data Easy Pro 30 min A bulk update corrupted tenant reports. Restore an older copy into quarantine while readers stay on the live store, then inspect the candidate separately.
- Route Through the App Easy Free with account 15 min Build a safe three-tier request path that keeps clients away from the database.
- Scale the Video Catalog Easy Pro 20 min Premiere night triples browse traffic and the single Catalog API folds. Clone the stateless tier behind a load balancer; both stores stay shared.
- Scale the Web Tier Easy Free with account 25 min Put a stateless app tier behind a load balancer and remove its single point of failure.
- Shorten the First Link Easy Pro 20 min A weekend script exposes the links database and mints short codes by hoping they don't collide. Put a Link API in front of the data and lease collision-free code blocks from a Key Issuer.
- Start the URL Frontier Easy Pro 25 min Turn seed URLs into a durable crawl loop instead of keeping the entire crawl in one fragile process.
- Store the First File Easy Pro 20 min The MVP stuffs every upload into a database row and backups now take all night. Give file bytes an object store and keep the database for metadata.
- Survive the Viral Link Easy Pro 25 min One viral link melts the single service doing two jobs. Split the redirect hot path from the create path and scale only the tier that is on fire.
- Build Video Search Medium Pro 45 min Build a searchable video catalog as an asynchronous projection of authoritative metadata.
- Cache DNS and Robots Rules Medium Pro 35 min Share DNS answers and robots policy across fetchers so repeated control lookups do not dominate the crawl or violate site rules.
- Cache the Hot Path Medium Free with account 55 min The product page hammers the database directly and melts under load. Design a read path with a load balancer, a cache and a replica, while keeping the client off the database.
- Cache the Redirect Medium Pro 35 min Reads outnumber writes a thousand to one and every redirect still hits the database. Cache the read path only (writes go around it) and give the links a replica.
- Cache the Video Watch Page Medium Pro 30 min Every premiere viewer reads the same watch-page rows. Cache the metadata reads; the video bytes keep their own uncached path to storage.
- Checkpoint Before Parsing Medium Pro 45 min Split unreliable network fetches from CPU-heavy parsing with an immutable page checkpoint and a second durable handoff.
- Count the Clicks Medium Pro 40 min Marketing wants click counts, but writing a row during every redirect doubles latency. Stream clicks through a durable queue into a dedicated Click Store, and keep them off the links table.
- Deduplicate Discovered URLs Medium Pro 35 min Canonicalize every discovered link and claim it in one shared seen-URL ledger before it can re-enter the frontier.
- Deliver Chat Attachments Medium Pro 35 min Photos are flowing through chat servers. Authorize with the API, upload directly to object storage, and read through the edge.
- Deliver Video from the Edge Medium Pro 35 min Separate playback authorization from high-volume media delivery through a CDN.
- Derive a Search Index Medium Pro 40 min Users want full-text search, but LIKE '%term%' on the primary database is slow and dangerous. Keep the database as the source of truth and project committed changes into a search index.
- Download from the Edge Medium Pro 35 min A shared file went out to ten thousand recipients and every byte flowed through the Share API. Let the edge serve bytes while the API only decides who may have them.
- Expire the Hold Medium Pro 40 min 11,000 seats are stuck on dead phones after the sale, and a laptop that wakes up can still pay for a hold from an hour ago. Keep the stadium sellable.
- Fan Out Home Timelines Medium Free with account 45 min Reading every followed author on demand is collapsing the database. Publish post events and materialize timelines asynchronously.
- Fan Out Notification Channels Medium Pro 35 min One worker now contains email, SMS, and push logic. Publish once to a topic and fan out to independent channel consumers.
- Make Payment Idempotent Medium Pro 35 min Queue redelivery is charging customers twice. Give every payment worker the same durable idempotency ledger and provider path.
- Persist Chat Messages Medium Pro 35 min Slow message storage blocks socket loops. Publish accepted messages to a durable broker and persist them with redundant writers.
- Process Video Uploads Medium Pro 45 min Move large video uploads off the request path and process them through a durable asynchronous pipeline.
- Publish the Seat Map Medium Pro 40 min 10,000 fans polling the seat map are starving the ledger that decides who gets each seat. Keep both working without selling a seat twice.
- Queue Notification Delivery Medium Pro 30 min Provider latency now holds campaign requests open. Accept quickly, enqueue durably, and let a delivery worker perform the slow external work.
- Rate-Limit at the Gateway Medium Pro 40 min One scraper hammers the API and every real user pays for it. Put a gateway in front that counts requests in a shared store and sheds abusive traffic before it reaches the app.
- Rebuild from Snapshot and Log Medium Pro 35 min Combine a consistent snapshot, its retained event suffix, and durable replay progress to rebuild without copying corruption.
- Redirect from the Edge Medium Pro 30 min Users on other continents pay hundreds of milliseconds of network for a sixty-byte redirect. Answer popular links at the edge and keep the origin as the source of truth.
- Reserve Before Payment Medium Pro 35 min Customers are charged for stock that vanished. Reserve inventory first, then hand payment work to a durable queue.
- Scale Real-time Connections Medium Pro 30 min One connection host cannot survive a deploy. Load-balance interchangeable gateways and move presence into shared state.
- Scan Before You Share Medium Pro 45 min One shared file full of malware would end the product. Turn every finished upload into an event and let redundant scanners record a verdict before anything becomes shareable.
- Separate Replay from Live Traffic Medium Pro 45 min Rebuilding old reports through the live event topic resends customer webhooks. Give recovery its own delivery lane, progress ledger, and projection-only consumers.
- Serve from the Edge Medium Pro 35 min Users a continent away wait on every image and script because one region serves the world. Put a global edge network in front and keep the origin for what actually changes.
- Sign with Build Identities Medium Pro 45 min A shared release key outlives every build. Bind each signing operation to a short-lived workload identity and log its evidence.
- Stop the Bots Medium Pro 40 min Bots behind 40,000 addresses hold 30% of the stadium and never trip the IP limiter. Make the printed four-ticket limit real.
- Survive a Database Failure Medium Pro 35 min The whole product runs on one database, so the night it dies the product dies with it. Add a standby replica the primary streams to and can fail over to.
- Upload Directly to Storage Medium Pro 35 min Request workers spend whole minutes shepherding gigabytes into storage. Authorize uploads at the API and send the bytes straight to object storage with a signed URL.
- Verify Before Release Promotion Medium Pro 55 min A valid signature from the wrong project reaches production. Put identity and provenance policy on every promotion path.
- Buffer the Write Spike Hard Pro 50 min Protect a database from bursty writes with a durable queue and redundant background workers.
- Claim the Front Row Hard Pro 55 min 20,000 claims in ten seconds pile up on a few hundred row locks, and fans buying in other stands time out too. Keep a hot stand from stalling the sale.
- Deduplicate Page Content Hard Pro 45 min Hash fetched bytes before expensive parsing so mirrors and alias URLs share one canonical content record.
- Fence the Retired Writer Hard Pro 50 min An old process wakes after cutover and overwrites recovered data. Enforce shared ownership epochs at the target.
- Guard the Vault Hard Pro 55 min The metadata database and the URL signing keys are one stolen laptop away from the internet. Put the admin plane behind a VPN inside real network boundaries.
- Handle Celebrity Fan-out Hard Free with account 1 h One celebrity post creates millions of writes. Combine pushed timelines for ordinary authors with a pulled celebrity index at read time.
- Honor Notification Preferences Hard Pro 45 min Channel fan-out ignores opt-outs during bursts. Put a preference cache on every delivery path without losing the durable source of truth.
- Index the Crawled Web Hard Pro 50 min Derive a replayable search index from the canonical corpus while keeping query traffic completely off the crawl pipeline.
- Keep Erased Data Erased Hard Pro 45 min Keep current erasure decisions in every historical restore path so an old backup cannot resurrect deleted data.
- Moderate and Index Posts Hard Pro 50 min Search indexes unreviewed content from an API dual write. Derive moderation and search asynchronously from committed posts.
- Observe the Shortener Hard Pro 50 min Redirects feel slow in some regions and click counts lag by hours, and nobody can prove where the time goes. Instrument the split system you built before guessing.
- Observe the Video Pipeline Hard Pro 55 min Carry useful telemetry across an asynchronous video-processing pipeline and into an operations stack.
- Operate the Notification Platform Hard Pro 1 h 15 min Synthesize a production notification plane with redundant APIs and consumers, shared preferences, managed secrets, and end-to-end telemetry.
- Operate the Onsale Hard Pro 1 h 30 min The provider slows down, no component fails, and the sale still gets worse for 20 minutes. Rebuild the onsale so the next slowdown does not snowball.
- Operate the Real-time Chat Platform Hard Pro 1 h 10 min Combine connection scale, durable messaging, attachment delivery, managed secrets, and telemetry into one operable chat system.
- Operate the Reliable Checkout Hard Pro 1 h 20 min Synthesize redundant checkout, idempotent payment, reliable order events, managed secrets, and correlated telemetry.
- Operate the Social Feed Hard Pro 1 h 30 min Combine edge media, redundant APIs, hybrid fan-out, derived search, managed secrets, and end-to-end observability.
- Operate the Upload Pipeline Hard Pro 1 h 20 min Turn a fragile file upload into a secure, observable asynchronous pipeline built for horizontal scale.
- Operate the Web Crawler Hard Pro 1 h 30 min Synthesize durable discovery, partitioned ownership, polite fetching, content identity, replayable indexing, quarantine, secrets, and telemetry.
- Partition Crawl Ownership Hard Pro 1 h 15 min Route every host to one durable frontier shard so crawl state can scale out without two partitions attacking the same origin.
- Publish Order Events Reliably Hard Pro 45 min Orders commit but fulfillment events disappear. Relay a durable outbox into a topic and isolate downstream consumers.
- Reconcile Before Cutover Hard Pro 50 min A rebuild completes with plausible but wrong totals. Require independent reconciliation before changing report routing.
- Recover Without the Control Plane Hard Pro 1 h 5 min The backup exists, but its catalog and keys need the failed control plane. Build and exercise an independently bootstrapped recovery.
- Recrawl for Freshness Hard Pro 50 min Turn a one-time crawl into an incremental system that schedules revisits from durable history and records only observed versions.
- Refund the Late Payment Hard Pro 1 h A payment result arrives 31 seconds after the hold expired. The seat has gone, the money has moved, and support hears about it two days later. Give every result one owner.
- Schedule Hosts Politely Hard Pro 45 min Replace FIFO crawling with host-aware scheduling that leases one origin at a time while the fleet stays busy across many hosts.
- Secure Video Operations Hard Pro 1 h A scraper site is hotlinking master files from the public bucket. Lock the origin in a private subnet, sign every upload, and make the CDN the only way in.
- Shard the Database Hard Pro 45 min The dataset outgrew the biggest machine you can rent and one database can't hold it. Split the data across shards and route each key to the shard that owns it.
- Verify Releases Without Egress Hard Pro 1 h 25 min An isolated release zone cannot call public signing services. Import complete evidence and update trust separately from verification.
- Witness the Release Checkpoint Hard Pro 1 h 30 min A log can present two individually valid histories. Require independent witnesses with durable checkpoint memory before importing release evidence.
Refactoring 51
C# refactoring exercises →- Dedupe the Field Validators Easy Free 10 min Three fields, three identical validation blocks.
- Dedupe the Menu Renderer Easy Pro 10 min Starters, mains and desserts, rendered by three identical loops.
- Dedupe the Statistics Easy Pro 12 min Min/max/avg computed three times over three arrays.
- Flatten the Config Fallbacks Easy Pro 10 min Three levels of default-chasing, one nested if per level.
- Flatten the Cursor Decoder Easy Pro 20 min A cursor envelope is validated inside a deep branch pyramid. Extract canonical number parsing and flatten the protocol guards.
- Flatten the Date Window Easy Pro 12 min Is the date inside the campaign window? Nested month/day comparisons say maybe.
- Flatten the Null Checks Easy Free 10 min An address printer hiding at the bottom of four nested ifs.
- Flatten the Withdrawal Checks Easy Pro 12 min An ATM withdrawal buried under five nested approval checks.
- Split the Tennis Score Easy Free 15 min The tennis kata: love, deuce and advantage in one long method.
- Tame the Grade Calculator Easy Free 15 min Letter grades with bonuses, written as a wall of nested ifs.
- Tame the Parking Garage Easy Pro 15 min Three vehicle types, three pasted fee blocks, one rate table waiting to exist.
- The Expense Report Easy Pro 15 min The expense-report kata: printing, summing and limit-checking in one method.
- Dedupe the Tier Calculators Medium Pro 18 min Bronze, silver and gold pricing methods that differ by one constant.
- Flatten the Category Walk Medium Pro 18 min Find the deepest category path without four levels of flags.
- Flatten the Permission Check Medium Pro 15 min Role-resource-action rules expressed as a nesting pyramid.
- Flatten the Retry Plan Medium Pro 15 min Exponential backoff delays computed inside three nested ifs and a flag.
- Flatten the Rule Matcher Medium Pro 15 min A found-flag, a nested loop and three breaks - for a one-line question.
- Flatten the Wizard Steps Medium Pro 15 min Signup wizard routing buried in step-by-step nesting.
- One Exporter, Three Formats Medium Pro 18 min CSV, pipe and tab exporters that differ by exactly one character.
- Separate Terminal Replay Medium Pro 30 min Cursor motion, overwriting, tabs, and line emission are interleaved in one loop. Give the replay state a clear boundary.
- Split the Bowling Scorer Medium Pro 20 min The classic bowling kata, graded on method size.
- Split the CSV Import Medium Pro 22 min Parse, validate and count in one sixty-line method.
- Split the DNS RRset Report Medium Pro 35 min DNS normalization, RRset aggregation, and alias diagnostics share one long method and four parallel dictionaries. Separate record identity from reporting.
- Split the Invoice Builder Medium Pro 18 min Item lines, subtotal, tax and total interleaved in one method.
- Split the Order Pipeline Medium Pro 22 min Validate, discount, ship and summarize - all in one breath.
- Split the Password Strength Check Medium Pro 22 min Length, character classes and a penalty, all in one long method.
- Tame Loan Eligibility Medium Pro 25 min A branch pyramid decides loans; flatten it into bands and guards.
- Tame the Access Rules Medium Pro 15 min Document access decided by one giant boolean expression.
- Tame the Delivery Estimator Medium Pro 20 min Carrier speeds and rush options, pasted three times over.
- Tame the Discount Engine Medium Free 25 min Untangle a copy-pasted discount calculator until every quality gate passes - without changing a single answer.
- Tame the Phone Bill Medium Pro 25 min Plan tiers with pasted overage logic - extract the plan table.
- Tame the Return Policy Medium Pro 22 min A decision tree of days, condition and receipts - currently a nesting pyramid.
- Tame the Roman Numeral Medium Pro 18 min A symbol-value ladder pasted twice inside one parsing loop.
- Tame the Shipping Calculator Medium Pro 30 min Refactor a working-but-tangled shipping calculator until every method stays under the complexity, nesting, length and duplication gates, without changing behavior.
- Tame the Tic-Tac-Toe Winner Medium Pro 20 min Eight winning lines checked by eight pasted conditions.
- Tame the Traffic Light Medium Pro 22 min Every state re-checks power and timer in its own nested block.
- Flatten the Game of Life Row Hard Pro 30 min Neighbor counting buried under nested loops and boundary ifs.
- Flatten the Spiral Matrix Hard Pro 35 min Spiral traversal with direction turns nested several deep.
- Gilded Rose Hard Free 40 min The canonical refactoring kata, one item per call, gated on method size.
- Split the Escaped Frame Decoder Hard Pro 55 min A serial protocol decoder mixes framing, escaped bytes, bounded buffering, checksum decisions, and chunk state in one method. Extract a recoverable parser without changing its wire behavior.
- Split the JSON Writer Hard Pro 30 min The same string-escape block pasted for keys and for values.
- Tame the Blackjack Hand Hard Pro 30 min Card values and soft-ace juggling tangled into one scoring method.
- Tame the Chess Move Hard Pro 35 min Move legality for six pieces packed into one branchy method.
- Tame the Elevator Hard Pro 35 min SCAN scheduling with two pasted min/max scans full of flags.
- Tame the Formula Evaluator Hard Pro 40 min Tokenizing and two precedence passes crammed into one method.
- Tame the Insurance Premium Hard Pro 35 min Age loads, risk multipliers and region fees, fused into one branch maze.
- Tame the Payroll Run Hard Pro 30 min Hourly, salaried and contractor pay rules braided into one method.
- Tame the Poker Hand Hard Pro 40 min Counts, straights and categories tangled into one long method.
- Tame the Vending Machine Hard Pro 30 min Price lookup and four pasted coin blocks in one method.
- The Statement Printer Hard Pro 35 min Fowler's theatrical invoice, compressed into one method.
- Untangle the Rollout Reducer Hard Pro 45 min Generation checks and deployment transitions are tangled across parallel dictionaries. Preserve stale-event and terminal-state rules while separating the reducer.
Architecture 33
C# architecture exercises →- A Repository Out of Place Easy Pro 10 min A concrete
*Repositoryhas settled into the core, right next to the port it implements. Move the role to the layer where it belongs; renaming it to dodge the placement rule trips the naming rule instead. - Fakes Don't Ship Easy Pro 15 min A test stub lives in the core and the checkout quietly falls back to it when nobody injects a gateway. Evict the stub to the testing namespace and make the dependency mandatory; a convenient default is a production code path.
- Keep HTTP at the Edge Easy Pro 20 min The returns application accepts a web request type directly, so transport points inward and the controller has no real use-case boundary. Map HTTP at the edge and drive an application-owned port.
- Keep Startup Out of Requests Easy Pro 20 min The search request path initializes its index on every call. Keep bootstrap work at the host boundary and lend the application only the initialized query capability.
- New Is Glue Easy Pro 15 min The port exists, the adapter implements it, and the core news the concrete anyway. One
newin the wrong place welds the core to infrastructure; hand the wiring to the composition root. - The Clock Is a Dependency Easy Pro 20 min A hotel's cancellation rule and its receipts both read a static infrastructure clock, so the core depends outward and nobody can choose the date it runs against. Hand the core a clock through its constructor and the domain a plain date, so a service that runs for days still dates every cancellation correctly.
- Caching Is an Adapter Medium Pro 30 min A quote use case memoizes prices with an infrastructure cache inside its own loop, so a storage tactic lives in the application. Move caching into a decorator on the price port, and let the composition root decide how long each cache lives.
- Compose Modules, Not Their Internals Medium Pro 35 min In a clinic's modular monolith, Appointments holds Billing's internal invoice book and the host news up module internals by hand, while Pharmacy already bills through a contract. Compose every module through its entry point, and keep every invoice number unique across the clinic day, whichever module asked for it.
- Config Is Infrastructure Medium Free 25 min The shipping core reads a framework configuration type directly, welding the domain to infrastructure. Invert it behind a core-owned options port, and don't just rename the framework wrapper into the core, which trips a second rule.
- Move the Port Home Medium Free 25 min A
*Portabstraction is declared beside its adapter, so the core reaches outward to see its own port. Move the single port into the core; duplicating it leaves a stray copy that fails the role-placement rule. - Preserve the Opaque Cursor Medium Pro 25 min An export invents offsets from row counts even though the storage service owns continuation tokens. Hide adapter details behind materialized pages and return every opaque token unchanged.
- Propagate the Caller's Cancellation Medium Pro 25 min A shard scan checks cancellation between probes but strips it from the adapter call. Keep caller-owned cancellation intact across the application port so an in-flight collaborator can observe it.
- Quarantine the Legacy Medium Pro 30 min The billing core calls a legacy ledger that speaks in public string fields and cent amounts, and parses its rows inline. Build an anti-corruption layer: one adapter owns the translation, and the core's allowlist catches any port that still leaks the legacy dialect.
- Record Events, Don't Send Them Medium Pro 35 min The Order aggregate emails the customer from inside Ship and Deliver, so the domain depends on an SMTP adapter and the mail leaves before the order is saved. Let the aggregate record domain events and have the application publish them through a port after each save, exactly once, even when the same order is saved again.
- Split the Read From the Write Medium Pro 25 min The history query formats its lines straight off the write-side aggregate, welding the two halves of a CQRS split together. A published snapshot already exists and sits unused; moving the aggregate into the contracts leaf instead trips the role rule.
- Strangle Behind the Port Medium Pro 30 min A pricing core chooses between legacy and replacement tax engines itself, so a temporary migration decision has become permanent domain coupling. Put coexistence behind one core-owned port and let an outer adapter route the strangler migration.
- The Core Doesn't Know Its Plugins Medium Pro 40 min A report host switches on format names and news up every plugin, and the plugins call back into the host and into each other for the report's currency rules. Let the composition root register plugins, refuse two plugins claiming one format, and hand each plugin the host's capabilities through a context the SDK publishes.
- The Layer Skip Medium Free 30 min A controller reaches past the application layer straight into infrastructure for the order total. Route the call back through the middle layer with a port the application owns; a thin pass-through that still touches infrastructure only moves the smell, it doesn't remove it.
- Two Sides of the Hexagon Medium Free 30 min A driving (web) adapter reaches the driven (persistence) adapter directly for a quick existence check. Inject the repository "via its interface" and you'll find the seam is still on the wrong side of the hexagon.
- Version the Edge, Not the Core Medium Pro 40 min The refund use case takes and returns v1's wire types, v2 is built on top of the v1 controller, and v2's refund reason reaches the policy through a field bolted onto v1's request. Give the application a version-neutral command that carries what the policy needs, so each API version is a thin sibling adapter.
- Break the Checkout Cycle Hard Free 50 min Orders, Pricing and Promotions import each other in a three-hop cycle while Pricing also reaches into Inventory's internals. Moving the obvious call only rotates the cycle; hoist the shared vocabulary into a kernel leaf and reach Inventory through its published port to turn every rule green.
- Commit State and Outbox Together Hard Pro 40 min A posting service saves its balance and publishes facts as separate operations. Replace the dual write with one optimistic commit capability that owns state and outbox intent atomically.
- Compensate Every Completed Step Hard Pro 45 min A booking coordinator knows concrete suppliers. Turn it into a saga over published step capabilities, preserving reverse compensation and draining remaining undo work when one release fails.
- Contracts Don't Depend Back Hard Pro 40 min The stable shared-contracts module depends back on a volatile feature to build a label. Invert the arrow without changing what Describe returns, and don't just drag the feature's service into the contract.
- Events Flow Up, Not Down Hard Pro 45 min A stable events hub reaches DOWN into a feature for a helper, and one feature reaches SIDEWAYS into a sibling to send an SMS. Cleaning up the hub is the obvious move, but it leaves the feature-to-feature edge red; only routing the sibling call through a hub-published port turns everything green.
- Evict the ORM From the Domain Hard Pro 35 min The domain entity inherits the ORM's base class and carries its own mapping, welding the most stable layer to a persistence framework. Moving the mapping alone won't free it; you must sever the base-type coupling and invert the persistence concern out.
- Funnel Through The Bus Hard Pro 50 min Orders calls Billing's and Notifications' internals directly while both peek back into Orders' internals, breaching the module boundaries and closing two cycles. A published bus and event already exist but sit unused. Republishing through the bus clears the direct calls and the cycle, yet the subscribers still reach into Orders to format their lines; only a fat-enough event turns every rule green.
- Invert the Callback Cycle Hard Pro 45 min Notifications calls back into Orders, closing a four-module cycle. A Shop.Contracts leaf already exists, but the back-edge is a call, not a shared data type, so hoisting another type into the leaf does nothing, and a contracts type that imports Orders trips the leaf-purity rule. Invert the direction with an IOrderCallback port the leaf owns.
- Lock Down the Shared Kernel Hard Pro 35 min The stable kernel reaches UP into two features: it borrows tax math from Pricing and a rounding helper from Checkout. Inlining the obvious tax edge clears one rule but leaves the allowlist and the helper-placement rule red, because a single forbidden-pair fix misses the second back-edge. Pull EVERY borrowed helper down into the kernel to turn all three green.
- Own Your Data Boundary Hard Pro 45 min Billing bypasses Orders' published surface and reads its internal database rows directly. Route the question through an Orders-owned query API, but do not mistake a port that returns the private row for a real boundary.
- Split the God Port Hard Pro 40 min One fat warehouse interface serves a consumer that only reads and a consumer that also reserves, so reporting can see a method it must never call. Splitting the interface is not enough: each half needs its own published namespace, and the behavior tests force one implementation behind both.
- The Shared Kernel That Wasn't Hard Pro 45 min Support routes tickets off a tier it reads straight out of Sales's private Customer entity. Decouple the two features through the shared kernel, but publishing the fat entity isn't sharing, it's fusing.
- Where Does the Policy Live? Hard Pro 40 min A late-fee business policy is stranded in Infrastructure because it depends on a concrete repository. Move it to the domain by inverting the dependency, not by relocating the file.
Secure coding 34
C# secure coding exercises →- Clamp the Page Size Easy Pro 12 min Bound a user-requested page size so a huge value cannot exhaust the server.
- Comment Renderer (HTML Injection) Easy Free 15 min Fix a stored-XSS hole in a comment renderer without breaking its output.
- Email Header Injection Easy Pro 12 min Reject recipient addresses that could break out of an email header line and forge new headers.
- Filename Sanitizer Easy Free 20 min Reduce an uploaded filename to a safe, single path segment.
- Link Scheme Allowlist Easy Pro 15 min Render a user-supplied link only when its scheme is one you trust, instead of blocklisting the dangerous ones.
- Log Forging (CRLF) Easy Free 12 min Stop user input from forging extra log lines with embedded newlines.
- Mass Assignment Guard Easy Free 12 min Decide which submitted fields may be applied to a record using an allowlist, not a blocklist.
- Negative Amount Refund Easy Pro 12 min Stop a refund whose amount or excess would move money the wrong way.
- Quarantine Spreadsheet Formulas Easy Pro 15 min Keep untrusted export cells from becoming spreadsheet commands, including whitespace and full-width prefixes.
- Scrub the Error Message Easy Pro 12 min Return a safe user-facing error that never leaks internal details.
- Shell Argument Quoting Easy Pro 20 min Quote customer-named files for a shell command so tar archives exactly those files, whatever characters the names contain.
- Upload Content-Type Allowlist Easy Pro 12 min Accept only the exact content types you actually support, instead of any value that looks close enough.
- Alternate IPv4 Spellings (SSRF) Medium Pro 35 min Read octal, hex, and shortened IPv4 hosts the way the URL parser does, so another spelling of an internal address cannot slip past the SSRF filter.
- Block Private Hosts (SSRF) Medium Free 15 min Reject internal hosts so a user-supplied URL cannot make the server call itself or its neighbors.
- CORS Origin Reflection Medium Pro 20 min Decide the Access-Control-Allow-Origin value by exact allowlist, not a suffix match an attacker can satisfy.
- Deduplicate Webhook Deliveries Medium Pro 20 min Select each new webhook event once, even when the same event is replayed inside a batch.
- Find the Trusted Forwarded Hop Medium Pro 20 min Recover the client from the trusted end of a proxy chain without accepting attacker-prepended identities.
- Host Allowlist Medium Pro 15 min Match a hostname against an allowed domain without the suffix-confusion bug.
- LIKE Wildcard Escape Medium Pro 15 min Escape LIKE wildcards so a search term cannot match everything.
- Lookalike Username Collisions Medium Pro 25 min Compare usernames by their Unicode-normalized, invisible-character-free form so a lookalike cannot claim a name that is already taken.
- Open Redirect Validator Medium Pro 15 min Allow only same-site redirect targets, blocking the off-site tricks.
- Password Reset Token Scope Medium Pro 20 min Bind a verified reset token to its subject, purpose, validity window, and one-time state.
- Path Traversal in Downloads Medium Pro 20 min Resolve a requested file path so it can't escape the download root.
- Quantity x Price Overflow Medium Pro 15 min Compute an order total that can't be wrapped by integer overflow.
- Quote SQL Identifier Medium Pro 15 min Quote a dynamic SQL identifier so an embedded quote cannot break out of it.
- Redact Card Numbers From Logs Medium Pro 30 min Mask every card number in a log line, in whatever shape it was written, before the line reaches log storage.
- Reject Ambiguous JSON Members Medium Pro 30 min Reject duplicate decoded property names at every nesting level before downstream parsers disagree.
- Snippet Expansion Bomb (Billion Laughs) Medium Pro 35 min Meter nested template snippets as they expand, so a few self-multiplying snippets cannot exhaust memory or CPU before the size check runs.
- Sort Column Allowlist Medium Pro 20 min Build an ORDER BY clause from a user-chosen column without opening a SQL injection hole.
- Tenant-Scoped Authorization Medium Pro 25 min Close a cross-tenant authorization hole that ownership and role checks alone cannot see.
- The Exploding SKU Regex Medium Pro 30 min Rewrite the backtracking validation patterns of a catalog import so one poisoned supplier file cannot pin a CPU core.
- Uniform Lookup Messages Medium Pro 15 min Return the same message whether or not an account exists, to stop enumeration.
- Reject Ambiguous HTTP Framing Hard Pro 40 min Reconcile repeated body-length headers and transfer coding before two HTTP hops disagree on request boundaries.
- Validate an Attenuated Delegation Chain Hard Pro 45 min Validate every grant ancestor so a delegated capability cannot regain permissions, extend expiry, or switch resources.
Test writing 38
C# unit testing exercises →- Test Signed Time Buckets Easy Free 15 min Write boundary tests for floor-based time buckets, where negative timestamps expose truncation bugs.
- Test the Clamp Function Easy Free 12 min You're given a correct clamp function. Write the tests that cover below, above, inside, and the boundaries.
- Test the FizzBuzz Rule Easy Free 12 min You're given a correct FizzBuzz. Write the tests that prove every branch, and that would catch a broken one.
- Test the Grade Boundaries Easy Free 12 min You're given a correct score-to-letter grader. Write the boundary tests that pin every cutoff and catch an off-by-one.
- Test the Max-of-Three Easy Free 12 min You're given a correct max-of-three function. Write the tests that prove it considers all three arguments.
- Test the Palindrome Check Easy Free 12 min You're given a correct palindrome check that ignores case and punctuation. Write the tests that cover every input class.
- Test the Quiet-Hours Window Easy Free 20 min You're given a correct quiet-hours check for notifications. Write the tests that pin both edges of the window and the day a held message goes out.
- Test the Temperature Converter Easy Free 12 min You're given a correct Celsius-to-Fahrenheit converter. Write the tests that pin the formula.
- Test the Vowel Counter Easy Free 12 min You're given a correct vowel counter. Write the tests that cover case, every vowel, and the letters that are not vowels.
- Test Stable Priority Ordering Medium Free 25 min Write operation sequences that distinguish priority order, FIFO ties, peeking, and queue-instance isolation.
- Test the Bracket Matcher Medium Free 20 min You're given a correct bracket matcher for (), [], and {}. Write the tests that pin type, order, and the unbalanced cases.
- Test the Caesar Cipher Medium Free 20 min You're given a correct Caesar cipher. Write the tests that pin wraparound, case, non-letters, and shift normalization.
- Test the Checkout Service Medium Free 35 min You're given a correct checkout service with three collaborators. Write recording fakes that prove what it does to each one, and in what order.
- Test the Expiring Cache Medium Free 30 min You're given a correct time-to-live cache that reads an injected TimeProvider. Write a clock you can move by hand and the tests that pin every expiry edge.
- Test the Leap-Year Rule Medium Free 15 min You're given a correct leap-year check. Write the tests that prove it, and that would catch a buggy one.
- Test the Order Status Workflow Medium Free 30 min You're given a correct order workflow. Write the tests that cover every state and call, and prove each refused move changes nothing.
- Test the Password Policy Medium Free 15 min You're given a correct password validator with four rules. Write tests that isolate each rule so a dropped one is caught.
- Test the Roman Numeral Converter Medium Free 15 min You're given a correct integer-to-Roman converter. Write the tests that pin the subtractive cases and the symbols.
- Test the Run-Length Encoder Medium Free 20 min You're given a correct run-length encoder. Write the tests that pin run boundaries, counts, and the empty case.
- Test the Triangle Classifier Medium Free 20 min You're given a correct triangle classifier. Write the tests that cover every shape and the invalid cases.
- Test Unicode Scalar Counting Medium Free 25 min Distinguish UTF-16 code units from Unicode scalars and reject unpaired surrogates at every position.
- Test Fenced Lease Ownership Hard Free 40 min Exercise expiry, renewal, ownership transfer, and stale-token rejection in a lease that must never reuse authority.
- Test the Bill Splitter Hard Free 30 min You're given a correct bill splitter that spreads leftover cents fairly. Write the tests that prove every cent is accounted for.
- Test the Bowling Scorer Hard Free 30 min You're given a correct ten-pin bowling scorer. Write the tests that exercise spares, strikes, and the bonus rolls.
- Test the Cart Discount Rules Hard Free 45 min You're given a correct cart pricer that stacks a volume discount, a coupon, and free shipping. Build the carts where a wrong rule order or a wrong rounding step changes the total.
- Test the Circuit Breaker State Machine Hard Free 40 min Drive closed, open, and half-open transitions with a fake clock and prove rejected calls never execute.
- Test the CSV Record Parser Hard Free 35 min You're given a correct CSV record parser. Write tests that pin quoting, empty fields, whitespace, and malformed input.
- Test the Interval Merger Hard Free 30 min You're given a correct interval merger. Write the tests that pin overlap, touching, containment, and sorting.
- Test the LRU Cache Hard Free 30 min You're given a correct LRU cache. Write the call sequences that prove it evicts the least-recently-used entry.
- Test the Luhn Checksum Hard Free 30 min You're given a correct Luhn card-number validator. Write the tests that pin the doubling, the digit reduction, and the rejects.
- Test the Next-Day Calculator Hard Free 30 min You're given a correct next-day date calculator. Write the tests that pin month, year, and leap-February rollover.
- Test the Progressive Tax Hard Free 30 min You're given a correct marginal income-tax calculator. Write the tests that prove each band is taxed marginally, not flatly.
- Test the Retry Executor Hard Free 35 min You're given a correct retry executor. Write tests that prove its attempt budget, exception policy, and call sequence.
- Test the RPN Calculator Hard Free 30 min You're given a correct reverse-Polish evaluator. Write the tests that pin operand order and the error cases.
- Test the Sliding-Window Rate Limiter Hard Free 30 min You're given a correct sliding-window rate limiter. Write the call sequences that prove the window slides and the limit holds.
- Test the Stock Reservations Hard Free 50 min You're given a correct stock ledger whose holds expire. Write the sequences that prove no unit is sold twice or stranded on an expired hold.
- Test the Transfer Ledger Hard Free 40 min You're given a correct transfer ledger. Write stateful tests that prove transfers are atomic and idempotent.
- Test the Version Comparer Hard Free 30 min You're given a correct dotted-version comparer. Write the tests that prove it compares numerically, not lexically.
Design principles 28
SOLID principles exercises →- A Preview Must Not Consume Work Easy Free 15 min Give queue observers a read-only capability and keep consumption behind an explicit command; repeated previews must leave the next item unchanged.
- Ask for the Interface Easy Free 15 min An order notifier news up its own SmtpEmailer and types the field as the concrete class, even though an IMessenger abstraction sits right next to it. Make the notifier ask for the interface in its constructor. Typing the field as IMessenger while still newing the concrete inside is not the fix.
- Stop the Train Wreck Easy Free 15 min A label printer reaches order.Buyer.HomeAddress.City to print one line, coupling itself to three classes for one string. Ask the order directly and talk to one neighbor, not a chain of strangers. Shortening the chain with a local variable does not shorten the coupling.
- An OrderId Is Not a CustomerId Medium Free 30 min OrderBook and its three callers identify orders and customers with bare ints, so a swapped argument compiles and quietly files an order under the wrong customer. Give each identifier its own value type that only ever holds a positive number, and bring the callers along without reopening the hole.
- Four Layers for One Formula Medium Free 35 min A report-card service reaches its one weighted formula through a factory, a calculator contract, a base class, and a selector, each added so it could be swapped one day. Take out every layer nothing varies behind and keep the one abstraction that really varies, without changing a single report card.
- Freeze the Money Medium Free 15 min Money pretends to be a value object: its arithmetic returns new instances, but its Amount and Currency are still publicly settable over a mutable field. Make it structurally immutable, and don't let the reflex
private setfool you; it hides the setter but leaves the backing field writable. - History Keeps a Checkpoint, Not Editor Internals Medium Free 25 min Capture immutable mementos that can be restored repeatedly while the history caretaker stays unaware of the editor’s stored representation.
- Kill the Global Counter Medium Free 15 min
Counterkeeps its running total in apublic staticfield every caller shares, and it's an open, inheritable class on top. Give the state one explicit owner instead of just hiding the field, and don't let the reflexprivate staticfix trick you into leaving the second smell standing. - Make Failure a Result Medium Free 25 min EnrollmentService throws for an expected full-course decision, forcing every caller to catch normal control flow. Return a sealed immutable EnrollmentResult, and do not leave an unused result beside the old exception path.
- Make Illegal States Unrepresentable Medium Free 35 min One mutable Parcel carries a status string plus fields that are null in most stages, and every desk operation guards the status at runtime. Model each stage as its own immutable type that carries only its data, refuses to exist without it, and offers only its legal moves, so an illegal move stops compiling.
- Null Object: No Branching Medium Free 20 min A cart guards a nullable discount with a null check at every use. Introduce a NoDiscount Null Object so the cart never branches on absence, but do not let the cart hard-code that default. The obvious 'default it inside the cart' move re-couples the cart to a concrete; the default belongs to the composition root.
- One Reason to Change Medium Free 35 min PaymentImporter reads bank-statement lines, decides duplicates against its own dictionary, and words the summary, so a new statement column, a move to a database, and new finance wording all edit the same method. Split it along those reasons to change, and let the store decide what counts as a duplicate at the moment it stores a payment.
- Own the Lease Until the Work Ends Medium Free 20 min Keep acquisition and deterministic disposal in one scope, including exception paths, while accepting any lease factory.
- Retire the Service Locator Medium Free 20 min A quote calculator fetches its rate table from a global ServiceLocator, so its one real dependency is invisible in every signature. Replace the locator with constructor injection. Caching the located table into a readonly field keeps the calculator quietly coupled to the global and leaves the key rule red.
- Shrink the Machine Interface Medium Free 20 min One fat IMachine interface forces the inkjet printer to fake a Scan it cannot perform, and the print queue to demand a scanner it never uses. Split the roles into IPrinter and IScanner. Keeping IMachine around as a composed sub-interface leaves the inkjet transitively welded to scanning and two rules red.
- Undo What Actually Happened Medium Free 35 min A stock room describes every adjustment twice, once in an Apply switch and again in an Undo switch. Turn each adjustment into a command that undoes itself behind a history that knows no stock, so a mis-keyed shipment can be reversed on its own without rolling back the deliveries that came after it.
- A Rule Tree Can Contain Any Rule Hard Free 40 min Replace a central tagged-tree evaluator with recursive rule objects that preserve child order, empty identities, and short-circuit behavior.
- Adopt the State That Comes Back Hard Free 35 min Move lifecycle decisions into state objects and adopt every returned successor, so state transitions remain substitutable across a whole sequence.
- Compose the Fees Hard Free 35 min Account fee variation is modeled by subclassing: PremiumAccount and StudentAccount each override MonthlyFee, so the base can never be sealed and every new flavor is a new class. Flatten the hierarchy into one sealed Account composed with an injected IFeePolicy. Extracting the policy but hard-coding a default inside the account trips the composition-root rule.
- Make It a Value Object Hard Free 30 min A Reservation is a mutable two-phase DTO that also hands out its backing guest list. Make it a real value object, frozen at construction, and don't let the obvious
private setfix fool you into leaving the collection leak wide open. - Make the Membership Contract Honest Hard Free 40 min An abstract Membership promises renewal even though lifetime memberships cannot renew, forcing RenewalService to recognize a concrete subtype before it can safely use the base contract. Split shared membership identity from the renewable capability, remove the lying inheritance, and make the service depend only on what it can honestly call.
- Notify Every Observer Hard Free 35 min BuildCoordinator reports completion to two constructor-injected observers, but its fields and constructor still name both concrete classes. Introduce one observer contract and make the coordinator broadcast through a collection without knowing which observers are present. A two-fake seam catches both concrete coupling and the tempting partial fix that notifies only the first subscriber.
- Program to the Abstraction Hard Free 25 min An IPaymentProcessor abstraction exists, but CardProcessor only duck-types it and a second implementer, LegacyCharger, honours it under the wrong name. Wiring up the obvious processor clears the implements rule but leaves the role's naming contract red. Make every payment method a true, conventionally-named drop-in over a proper abstract base.
- Seal the Aggregate Hard Free 25 min
Orderenforces a three-line cap inAddLinebut hands out its backingList<OrderLine>through a public, settable property. Seal the aggregate so callers can only change it through its methods, and don't let the obviousprivate setfix fool you into leaving the collection leak wide open. - Strategy Over the Switch Hard Free 35 min A price calculator switches on a plan-name string and news up each concrete strategy by hand. Extracting an IPricingStrategy looks like the fix, but a tempting in-class factory keeps the concretes wired into the calculator. Make the calculator depend only on the abstraction and let the composition root choose the plan.
- The Leaky Payment Port Hard Free 40 min A checkout service is welded to a Stripe client and passes vendor DTOs around. Someone half-extracted an IPaymentGateway port, but it leaks Stripe types through its own signature. Make the port vendor-neutral with a real anti-corruption layer, not an interface that smuggles the SDK through.
- Visit Every Invoice Line Hard Free 40 min Tax and printing each type-switch over invoice lines and fall back to a silent default, so a new line kind compiles and quietly goes untaxed. Rebuild both operations as visitors the lines dispatch to, so forgetting a kind becomes a compile error.
- Wrap It, Don't Flag It Hard Free 30 min An announcer dresses up messages with boolean flags, and every new dressing doubles the combination space inside one method. Rebuild it as stackable decorators over an IAnnouncer abstraction. Subclassing the plain announcer, or letting a decorator new up its own inner, fails the sealed and wraps-any rules.
Not sure where to start?
Two Sum is the usual first kata, and you can run it without an account.
Try it free, no signup