Programming Exercises
Practice with real problems and instant feedback.
Promise Timeout with Timer Cleanup
Wrap a promise with a deadline that rejects with a TimeoutError, while clearing the timer on settlement and preserving the original rejection reason.
Read and Normalize Filter State from a Query String
Parse repeated tag parameters with URLSearchParams, deduplicate them, clamp the page number, and validate the sort key.
Retry with Exponential Backoff and Cap
Implement an async retry helper with configurable attempts, exponential delays, a maximum delay cap, and a deterministic injected sleep function for testing.
Compute Reading Progress from Scroll Metrics
Calculate a clamped, rounded scroll percentage from scrollTop, scrollHeight, and clientHeight, handling short pages and overscroll.
Longest Substring Without Repeating Characters
Use a sliding window with a last-seen index map to find the length of the longest substring that contains no repeated character.
Sliding Window Rate Limiter
Implement a sliding-window limiter that expires timestamps on the trailing edge, decides events at exact boundaries, and reports allowed and denied ids.
Deterministic Topological Sort for Dependencies
Sort build targets so dependencies come first, breaking ties alphabetically with Kahn's algorithm, and detect cycles that leave nodes unprocessed.
Kahn's Algorithm for Course Ordering
Compute a valid topological ordering of a directed graph with Kahn's BFS algorithm, returning an empty array when the graph has a cycle.
Container With Most Water
Use two pointers moving inward from both ends to find the maximum water area between pairs of vertical lines.
Count Connected Components with Union-Find
Build a disjoint-set forest with path compression and union by rank, then count the connected components of an undirected graph.
Merge and Serialize URL Query Parameters
Merge default and override query parameters, drop nulls, repeat array values, sort keys, and serialize with URLSearchParams-compatible percent encoding.
Virtual List Window Calculator
Compute the visible slice, overscan bounds, and top offset for a fixed-height virtual list, including partial rows and edge cases at the end of the list.
Combination Sum with Backtracking
Generate every unique combination of candidates that sums to a target, allowing unlimited reuse of each candidate.
Count Unique Grid Paths with Obstacles
Use a one-row dynamic programming table to count monotone paths through a grid while treating blocked cells as impassable.
Check Bipartiteness with BFS Coloring
Color an undirected graph with two colors using BFS and report whether any edge connects vertices of the same color.
K Largest Elements with heapq
Use Python's heapq.nlargest to return the k largest values of a list in descending order, including duplicates.
Minimum Meeting Rooms with a Heap
Sort meetings by start time and use a min-heap of end times to count how many rooms are needed at peak overlap.
Sieve of Eratosthenes
Generate every prime up to n with the sieve of Eratosthenes, marking multiples starting from each prime's square.
Minimum Size Subarray Sum
Use a growing and shrinking window to find the shortest contiguous subarray whose sum reaches a target value.
Find All Anagrams in a String
Slide a fixed-width window over the text while comparing character counts with the pattern to collect anagram start indices.
Word Dictionary with a Prefix Trie
Implement a trie supporting word insertion, exact lookup, and prefix checks, then replay search and prefix queries.
Find the Redundant Edge with Union-Find
Scan edges of a near-tree graph with union-find and return the first edge whose endpoints are already connected.
Asyncio Rate Limiting with Semaphore
Limit concurrent async jobs with asyncio.Semaphore, keep results in input order, and track the observed peak concurrency.
Atomic File Replacement with Rollback
Write text to a temporary sibling file, flush and fsync it, then atomically replace the destination while cleaning up on failure.
Aggregate CSV Rows by Category
Parse CSV text with csv.DictReader, validate amounts, and return category totals ordered by amount descending then name.
Dijkstra Shortest Path with a Heap
Compute single-source shortest paths on a non-negative weighted digraph with a min-heap and stale-entry skipping.
HTTP GET with Retry and Backoff
Retry transient HTTP 429 and 5xx failures with bounded exponential backoff, decode JSON on success, and surface permanent errors immediately.
Stream and Filter JSON Lines
Parse newline-delimited JSON events, keep purchases above a threshold, and count malformed lines without aborting the stream.
LRU Cache with OrderedDict
Implement a fixed-capacity least-recently-used cache with constant-time get and put using collections.OrderedDict and move_to_end.
Merge Overlapping Intervals (Python)
Sort intervals by start and merge overlapping or touching ranges into a minimal disjoint set in linear time after sorting.
Producer-Consumer with a Bounded Queue
Coordinate producer and consumer threads with queue.Queue, sentinel shutdown, and proper joins to process every item exactly once.
Retry Decorator with Exception Filtering
Build a decorator that retries only selected exceptions, applies exponential backoff, and re-raises the final failure unchanged.
Search in a Rotated Sorted Array
Find a target index in a rotated sorted array in logarithmic time by detecting which half is still sorted at each step.
Context Manager That Guarantees Cleanup
Implement a transaction context manager that commits on success, rolls back on exceptions, and always marks the resource closed.
Maximum Sum of a Fixed-Size Window
Find the largest sum of any contiguous subarray of length k in one pass, then explain why the sliding window stays linear.
Thread Pool Fan-Out with ThreadPoolExecutor
Run independent I/O-bound jobs concurrently with ThreadPoolExecutor, preserve input order, and surface the first worker exception.
Topological Sort with Kahn's Algorithm
Order dependency graphs by repeatedly taking the smallest zero-indegree node, and detect cycles when fewer than n nodes are emitted.
Trie with Prefix Counting
Insert lowercase words into a trie, test full-word membership, and count how many inserted words start with a given prefix.
Monthly Cohort Retention with Conditional Counts
Build acquisition cohorts with MIN and date_trunc, then measure month-one retention in PostgreSQL using COUNT DISTINCT with a FILTER clause.
Delete Duplicate Customers Keeping the Newest Row
Use ROW_NUMBER in a CTE to rank duplicate emails, then delete every row except the most recently updated record with a stable id tie-break.
First Purchase per Customer with DISTINCT ON
Use PostgreSQL DISTINCT ON to return each customer's earliest order, including a deterministic id tie-break, while excluding customers who never ordered.
Find Missing Invoice Numbers with generate_series
Detect gaps in a PostgreSQL invoice number sequence using generate_series and NOT EXISTS, then return every missing identifier in ascending order.
Median Salary per Department with PERCENTILE_CONT
Compute median and average salary per department in PostgreSQL using PERCENTILE_CONT and AVG, then round both results to two decimals.
Month-over-Month Revenue Growth with LAG
Calculate month-over-month revenue growth in PostgreSQL with the LAG window function, guard division by zero, and label the first month as NULL.
Three-Day Moving Average with a RANGE Window
Compute a calendar-based three-day moving average in PostgreSQL with a RANGE window frame, then compare it with a row-based frame on gappy data.
Sessionize Page Views with a 30-Minute Timeout
Assign page views to sessions using LAG and a running SUM, starting a new session after 30 minutes of inactivity for each user.
Top Two Products per Category with DENSE_RANK
Rank products by price inside each category with DENSE_RANK, then keep the top two price levels while preserving ties as separate rows.
Atomic Funds Transfer with a Transaction
Implement an atomic account transfer in PostgreSQL using BEGIN, row locks, and a DO block that raises an exception to roll back insufficient funds.
Lower and Upper Bounds in a Sorted Array
Implement generic lower-bound and upper-bound binary searches and return both insertion points for a target value.
Edit Distance with Rolling DP
Compute the Levenshtein distance between two strings using a one-dimensional dynamic programming row that is updated in place.
Exhaustive Reducer with assertNever
Model counter actions as a discriminated union, reduce them with a switch that ends in assertNever, and record each resulting count in a history array.
Iterative DFS Preorder on an Adjacency Map
Traverse a directed graph without recursion using an explicit stack, producing a deterministic preorder with sorted neighbor visits.
Longest Increasing Subsequence in O(n log n)
Use patience sorting with binary search over tail values to compute the length of the longest strictly increasing subsequence.
Count N-Queens Solutions with Backtracking
Count placements of n non-attacking queens on an n by n board using column and diagonal sets with backtracking.
Generic Priority Queue with a Comparator
Implement a typed binary min-heap priority queue that accepts any element type and a custom comparison function.
Quickselect for the Kth Smallest Element
Find the kth smallest value with three-way partitioning that keeps expected linear time even when the array has many duplicates.
Result Pipeline with Short-Circuiting
Implement Result, map, flatMap, and mapErr, then compose a parse-double-validate pipeline where the first failure skips every later step.
Spiral Matrix Traversal
Walk an m by n matrix in clockwise spiral order by shrinking top, bottom, left, and right boundaries after each side.
Trie Autocomplete with Prefix Suggestions
Store words in a trie and return up to k completions for a prefix in lexicographic order using depth-first collection.
Typed CSV Parser with Quoted Fields
Parse CSV text with quoted commas and doubled quotes, map columns through typed converters, and return strongly typed row objects from a header-driven schema.
Generic Deep Merge for Config Objects
Implement a recursive deep merge that replaces arrays, skips undefined values, returns a new object, and uses a mapped DeepPartial type for the patch parameter.
Typed Event Emitter with On, Once, and Off
Build a generic event emitter whose on, once, and emit methods are keyed by an event map, so payloads are type-checked and subscriptions can be removed.
Typed JSON Fetch with Validation
Write fetchJson with a generic type predicate, distinct HTTP, JSON, and shape errors, and an injectable request function so the whole flow runs without a network.
Composable Typed Form Validators
Create reusable validator functions with a shared error union, run them per field in a fixed order, and aggregate only the first error for each field.
Generic LRU Cache with Eviction Log
Implement a generic LRU cache with get, set, delete, and ordered entries, recording every evicted key-value pair so tests can assert the eviction policy.
Type-Safe Dot-Path Getter
Implement getPath with template-literal types that resolve dotted object keys and numeric array indexes, returning the precise value type or undefined.
Typed Pipe with Overloads
Implement pipe overloads for one through four unary functions, preserving every intermediate type, and use them to build slugify, shout, and length presets.
Type-Safe Query Builder with Parameters
Build a small SQL query builder typed over a row shape, collecting WHERE values into ordered placeholders and rendering SELECT, ORDER BY, and LIMIT clauses.
Typed Route Matcher with Template Literals
Extract named parameters from route patterns using template-literal types, match URL segments at runtime, and decode percent-encoded path values.
Typed Finite State Machine
Build a generic state machine over a transition table that rejects invalid events with a descriptive error and records every state visited.
Associative Array Counting
Use bash associative arrays to count occurrences of items in a list with proper key-value storage and iteration patterns.
Conditional Tests and File Checks
Use bash test operators for file existence, string comparison, and numeric conditions.
Exit Codes and Error Handling
Use bash exit codes and set -e for robust error handling in scripts with proper fail-fast behavior and pipeline safety.
Function Arguments and Return
Write bash functions that accept arguments and return values via echo and exit codes.
Getopts for CLI Options
Parse command-line options and arguments using bash getopts built-in with comprehensive examples and best practices for production use.
Heredoc for Multiline Templates
Use bash heredoc syntax for generating multiline text files and configuration templates.
Parallel Job Execution
Run multiple bash commands in parallel using background jobs and wait for completion.
Pipeline Text Filtering
Use bash pipelines with grep, sort, and uniq to filter and analyze text data streams.
String Manipulation Patterns
Use bash parameter expansion for substring extraction, replacement, and case conversion.
Trap for Cleanup on Exit
Use bash trap to run cleanup functions on script exit, interrupt, or error signals.
Keyframe Animations
Create smooth CSS animations using keyframes with timing functions and delays.
Container Queries for Components
Use CSS container queries for responsive components that adapt to their container size.
CSS Custom Properties Theming
Use CSS custom properties for dynamic theming with runtime variable updates.
Flexbox Navigation Bar
Create a responsive navigation bar using CSS flexbox with space-between alignment.
Fluid Typography with Clamp
Use CSS clamp function for fluid typography that scales smoothly between viewport sizes.
CSS Grid Dashboard Layout
Create a dashboard layout using CSS Grid with named template areas for responsive panels.
Pseudo-Elements for Decorations
Use CSS pseudo-elements ::before and ::after for decorative content and effects.
Media Query Breakpoints
Use CSS media queries for responsive design with mobile-first breakpoint strategy.
Scroll Snap for Carousels
Use CSS scroll-snap properties for touch-friendly carousel and gallery scrolling.
Smooth CSS Transitions
Use CSS transitions for smooth state changes with custom timing and properties.
Go Channel Communication
Use Go channels for safe communication between goroutines with buffering and direction restrictions.
Channel Select Multiplexing
Use Go select statement to multiplex across multiple channels for concurrent communication.
Go Concurrent Pipeline
Build a multi-stage concurrent pipeline in Go using channels and goroutines for streaming data processing.
Go Context Cancellation
Use Go context package for cancellation propagation, timeouts, and request-scoped values across goroutines.
Context with Timeout
Use context.WithTimeout to cancel long-running operations and prevent resource leaks.
Defer for Resource Cleanup
Use Go defer statements to ensure resource cleanup runs even when errors occur.
Go Error Handling
Practice Go error handling patterns including checking errors, wrapping, and custom error types.
Error Wrapping and Unwrapping
Use Go 1.13+ error wrapping with fmt.Errorf and errors.Is for contextual error handling.
Go Generic Constraints
Use Go generics with custom type constraints to implement type-safe algorithms for ordered and numeric types.
Generic Min Function
Use Go 1.18+ generics to implement a type-safe min function for any ordered type.