Programming Exercises
Practice with real problems and instant feedback.
LZW Compression with Self-Checking Decode
Implement LZW compression over an ASCII dictionary, then decode the emitted code stream back to text and verify the round trip restores the original input exactly.
Mini Mustache Template Renderer
Render a mustache-style template with escaped variables, triple-stash raw variables, boolean sections, and array sections using the dot placeholder.
Retry Delays with Full Jitter
Compute full-jitter exponential backoff delays from injected random seeds, capping the exponential growth and rounding each delay to an integer.
Ring Buffer with Overwrite Reporting
Implement a fixed-capacity ring buffer where pushing onto a full buffer overwrites the oldest item, and report pop results plus every overwritten value.
Roman Numeral Conversion
Convert integers to Roman numerals using the standard greedy table including subtractive pairs, covering values from 1 through 3999.
Reverse Polish Notation Calculator
Evaluate an arithmetic expression in postfix notation with a stack, using truncating integer division, and report the final value.
Skip List with Deterministic Levels
Insert numbers into a skip list whose node levels come from a deterministic hash rule, then report sorted order, search hits, and per-level node counts.
Sliding Window Maximum with Monotonic Deque
Compute the maximum of every length-k window over an integer array using a monotonic deque in linear time, including edge cases at array boundaries.
Deadline Budget Propagation
Propagate a single deadline budget across pipeline stages, reporting the budget each stage starts with and whether the pipeline exceeded the total.
Token Bucket Rate Limiter Simulation
Simulate a token bucket over a timestamped request stream: refill tokens continuously up to capacity, admit requests that fit, and report per-request verdicts.
Build Order via Topological Sort
Resolve build dependencies with Kahn’s algorithm using a lexicographically smallest frontier, reporting a valid order or detecting a cycle.
Trie Prefix Autocomplete
Insert words into a trie and enumerate dictionary-ordered completions for a query prefix, including the empty prefix that lists every word.
Union-Find with Size Tracking
Merge sets with union by size and path compression while reporting the largest connected component size after every union operation.
URL Normalization for Cache Keys
Normalize URLs into canonical cache keys: lowercase scheme and host, drop default ports, sort query parameters, and strip fragments.
Weighted Shortest Processing Time Scheduling
Order jobs by weight divided by processing time to minimize the sum of weighted completion times, and report the schedule and its cost.
Batch Rename Photos with a Dry Run
Safely renumber IMG_*.jpeg files into zero-padded photo names, defaulting to a dry run and refusing to overwrite any existing target.
Sum a CSV Column with awk
Read a CSV amount column with awk, validate every numeric value, skip the header, and print the row count plus a two-decimal total.
Loop Over a Date Range in Bash
Validate ISO dates, compare them lexicographically, and iterate inclusive days with GNU date arithmetic while printing each weekday.
Find Duplicate Files by SHA-256 Hash
Hash every regular file with sha256sum, group identical digests with sort and awk, and print only the paths that have at least one duplicate.
Parse INI Sections with awk
Parse an INI file with awk, skip comments, track the current section, trim keys and values, and optionally filter output to a single section.
Count Log Levels with awk and sort
Parse bracketed severity labels from a log file with awk, count each level, and sort the summary by descending count then level name.
Render an Aligned Table with printf
Read colon-separated records, validate sizes, truncate long names with an ellipsis, and align a header and rows using printf widths.
Compare Two Lists with comm and Process Substitution
Use comm with process substitution to sort and compare two name lists on the fly, reporting entries missing from and unexpected in the actual list.
Update a Config Value with sed In Place
Safely rewrite a key=value setting with sed, escape replacement metacharacters, keep a .bak backup, and report whether anything changed.
Verify a SHA-256 Manifest
Read a sha256sum manifest, check each referenced file, report OK, FAILED, or MISSING, and exit non-zero when any entry fails.
Top Words with tr, sort and uniq
Normalize text to lowercase words with tr, filter stop words in awk, and rank the most frequent terms using sort, uniq, and a final limit.
Keep Card Images Proportional with aspect-ratio
Reserve a 16:9 media box with aspect-ratio, crop images with object-fit cover, and keep a padding fallback for older engines.
Scale Section Spacing with clamp()
Use clamp for fluid section padding and a measured text column so spacing grows with the viewport but stays within limits.
Theme a Card with Custom Properties and Color Scheme
Define semantic color tokens on :root, override them in a dark color-scheme media query, and consume them in a card component.
Create a High-Contrast :focus-visible Ring
Replace default outlines with a 3px focus ring that appears for keyboard users and stays hidden for pointer clicks.
Lay Out a Page with Named Grid Areas
Define a four-region page with grid-template-areas, then collapse it to one column below 48rem without horizontal scrolling.
Reveal Field Errors with :has() and :user-invalid
Show inline error text and an error border only after a field is submitted or blurred, using :has and :user-invalid.
Use Logical Properties for Direction-Agnostic Layout
Replace left and right spacing with margin-inline, padding-block, and inset-inline-start so the layout mirrors in RTL.
Clamp Paragraphs to Three Lines
Truncate a card excerpt to three lines with line-clamp and overflow hidden while keeping the full text in the DOM.
Respect Reduced Motion in a Toast
Animate a toast with transform and opacity, then disable the movement for users who prefer reduced motion while keeping the message visible.
Sticky Header Without Hiding Anchor Targets
Pin a site header with position sticky and offset in-page anchors with scroll-padding so headings stay visible after jumps.
Align Form Labels with CSS Subgrid
Build a two-column form where each fieldset inherits the parent grid tracks with subgrid, with a fallback for old browsers.
Binary Search on Ship Capacity
Find the smallest daily ship capacity that moves ordered packages within a day limit using monotonic feasibility and binary search.
Coin Change with Fewest Coins
Solve unbounded coin change with bottom-up dynamic programming and return -1 when the target amount is unreachable.
Parse a Sectioned INI Config
Scan INI text into nested maps, supporting comments and blank lines while rejecting malformed entries with exact line numbers.
Cancel Siblings on First Error
Implement a minimal errgroup with context cancellation so the first failing goroutine stops its peers and Wait returns that error once.
Read the Last N Lines of a File
Seek backward from end-of-file in fixed chunks to return the last n lines without loading the entire file into memory.
HTTP JSON Client with Timeout
Send context-aware GET requests, turn non-200 statuses into typed errors, cap the body size, and decode JSON safely.
API Key HTTP Middleware
Wrap an http.Handler with an API-key gate that returns JSON 401 responses and passes authorized requests to the next handler.
Priority Queue with container/heap
Implement heap.Interface for tasks ordered by priority then name, supporting push, pop, and reordering an updated task.
Recover Panics in a Worker
Convert panics from job functions into ordinary errors with recover so one bad job cannot crash the whole batch.
Generic Fixed-Size Ring Buffer
Implement a generic ring buffer that overwrites the oldest item when full and snapshots values from oldest to newest.
Sentinel and Wrapped Errors
Define sentinel errors and a typed validation error, wrap them with context, and classify failures using errors.Is and errors.As.
Balanced Brackets with a Stack
Validate nested parentheses, brackets, and braces with a rune stack and report the first mismatched or unclosed position.
Token Bucket Rate Limiter
Implement a concurrency-safe token bucket that refills by elapsed time, supports bursts, and rejects calls when no token is available.
Union-Find with Path Compression
Implement disjoint sets with union by rank and path compression, then count connected components in an undirected graph.
Bounded Worker Pool with Ordered Results
Fan out indexed jobs to a fixed number of goroutines, collect results over a channel, and rebuild the input order before returning.
Mark Up an Accessible Breadcrumb Trail
Use a labelled nav element, an ordered list, and aria-current to expose the current page in a three-level breadcrumb.
Wire an Input to a Datalist Suggestion List
Connect a labelled search input to a datalist so browsers suggest framework names while still accepting free text.
Build a Glossary with Description Lists
Structure term and definition pairs with dl, dt, dfn, and dd so assistive technology understands the glossary relationships.
Build an FAQ with Native details and summary
Create collapsible FAQ answers with details and summary, keep heading structure, and rely on native expanded-state announcements.
Announce Form Errors with a Linked Summary
Add a focusable role=alert error summary that links to each invalid field and connects messages with aria-invalid and aria-describedby.
Group Radio Buttons with Fieldset and Legend
Use fieldset and legend to name a radio group, label every option, and keep the whole group to a single Tab stop.
Pair a Chart Image with figure and figcaption
Wrap a chart image and its explanation in figure and figcaption, with intrinsic dimensions and deferred loading.
Label progress and meter Elements
Add visible labels and fallback text to an upload progress bar and a disk-usage meter so values are understandable everywhere.
Add a Skip Link and Labelled Landmarks
Build a keyboard-first page shell whose skip link targets main content and whose header, navigation, main, and footer are labelled landmarks.
Mark Up Event Dates with time and datetime
Use time elements with machine-readable datetime attributes inside an ordered list of upcoming workshops.
Group Anagrams with Sorted Keys
Normalize each word into a sorted-letter key, group words in a TreeMap, sort every group, and print deterministic anagram lines.
Safe Increment with AtomicInteger and a Latch
Start eight workers simultaneously with CountDownLatch, increment a shared AtomicInteger 100,000 times each, and verify no updates are lost.
Aggregate Order Spend with flatMap
Flatten nested order items with flatMap, total each line, then group spend by customer and sort the result by amount descending.
Summarize Salaries by Department
Group employees with groupingBy, summarize salary statistics per department, round the averages, and sort departments by average descending.
Build an LRU Cache with LinkedHashMap
Extend LinkedHashMap in access order, override removeEldestEntry, and exercise get and put to observe least-recently-used eviction.
Merge Overlapping Intervals (Java)
Sort intervals by start and end, merge overlapping closed ranges in one pass, and reject intervals whose start exceeds their end.
Partition Paid and Unpaid Orders
Split orders with partitioningBy, compute counts and totals per partition, and find the largest unpaid order with a max comparator.
Producer-Consumer with a BlockingQueue
Coordinate one producer and two consumers through a bounded BlockingQueue, terminate them with poison pills, and verify the total sum.
Top K Frequent Numbers with a PriorityQueue
Count values with a HashMap, maintain the top k in a min-heap keyed by frequency, then sort the survivors by count and value.
Top Three Words from Lines with Streams
Tokenize lines into lowercase words, count frequencies with groupingBy, then sort by count descending and word ascending before limiting.
Compute Roving tabindex Moves for an ARIA Tab List
Implement the keyboard index math for an ARIA tab list with arrow keys, Home, and End, including wrapping at both ends.
Async Semaphore with Queued Tasks
Build a counting semaphore that limits concurrent async work, queues waiters fairly, and releases slots through a handoff instead of double-decrementing.
Generate All Permutations with Backtracking
Produce every permutation of an array of distinct integers in lexicographic order using recursive backtracking and a used flags array.
Counting Bits with Dynamic Programming
Build the popcount table for every number from 0 to n in linear time using the relation bits[i] = bits[i >> 1] + (i & 1).
Validate a Binary Search Tree
Check whether a level-order array with nulls represents a valid binary search tree using recursive open bounds.
Parse and Serialize Cookie Strings
Parse a document.cookie style header into a name-value map, handle duplicates and percent-decoding, then serialize a cookie with Path, Max-Age, SameSite, and Secure.
Validate a Username with Custom Messages
Return the first failing username rule in ValidityState order, gate messages until the field is dirty, and report overall validity.
Debounce with Cancel, Flush, and an Injected Clock
Build a debounce utility with cancel and flush methods, then drive it with an injected fake clock so bursts, cancellation, and forced flushes stay deterministic.
Deep Equality for JSON Values
Compare nested JSON values by structure rather than reference, handling arrays, key order, null, and length mismatches without relying on JSON.stringify.
Track Focus Return Targets for Nested Dialogs
Model a dialog focus stack that remembers each trigger element and returns focus to the most recent one when dialogs close.
Dijkstra Shortest Path with a Binary Heap
Compute the shortest path cost in a weighted directed graph using Dijkstra's algorithm backed by a hand-written binary min-heap.
Union-Find Components with Path Compression
Implement disjoint-set union with path compression and union by rank, then answer membership queries and count connected components after a batch of unions.
Minimum Coins for an Amount
Solve the coin change problem with bottom-up dynamic programming, returning the fewest coins needed or -1 when the amount is unreachable.
Resolve Delegated Click Actions from an Event Path
Walk a simulated event path from target to ancestor, find the closest data-action element, and read its dataset values.
Event Delegation Selector Matcher
Implement the matching logic behind event delegation: parse a compound CSS selector and walk an ancestor path to find the closest matching element.
Focus Trap Tab Cycle Index
Given focusable count, disabled indexes, and the current index, compute where Tab or Shift+Tab should move, skipping disabled elements and wrapping around.
Cycle Focus Inside a Modal Dialog
Return the next focusable index when Tab or Shift+Tab reaches the edge of a modal, wrapping focus back inside the dialog.
Convert FormData Entries into a Plain Object
Serialize form entries into an object that keeps repeated names as arrays and drops blank trimmed values.
Compute IntersectionObserver Visibility
Derive intersectionRatio and threshold visibility from target and intersection rectangles, rounded to two decimals.
Intersection Visible Ratio Calculator
Compute the fraction of a target rectangle visible inside a root viewport, clamping overlaps and handling zero-area targets the way IntersectionObserver ratios behave.
Insert and Merge Into Sorted Intervals
Insert a new interval into a sorted list of disjoint intervals, merging every overlapping neighbour and keeping the result ordered.
Resolve RFC 6901 JSON Pointers
Walk a JSON document with a JSON Pointer, decode the ~0 and ~1 escapes, validate array indexes, and report missing paths without throwing.
KMP Pattern Matching
Implement the Knuth-Morris-Pratt algorithm with a longest-prefix-suffix table to report every match position in linear time.
Latest-Request-Wins Response Gate
Model a UI request gate that aborts superseded requests, commits only the active response, and records stale completions that arrive out of order.
Build Polite Search Status Messages
Compose result-count announcements with correct pluralization, thousands separators, pending, and empty-query states.
Byte-Budgeted localStorage LRU Eviction
Simulate a size-limited browser storage cache: track key and value bytes, promote reads, evict the least recently used entry, and reject oversized writes.
Min-Heap Priority Queue with Stable Ties
Implement a binary min-heap with push, pop, and peek where insertion order breaks priority ties, and drive it from a JSON operation log.
Daily Temperatures with a Monotonic Stack
Use a decreasing monotonic stack to compute, for each day, how many days pass until a warmer temperature appears.