Learning Resources

Programming Exercises

Practice with real problems and instant feedback.

3 / 6

intermediatejavascript

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.

basicjavascript

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.

intermediatejavascript

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.

basicjavascript

Compute Reading Progress from Scroll Metrics

Calculate a clamped, rounded scroll percentage from scrollTop, scrollHeight, and clientHeight, handling short pages and overscroll.

intermediatejavascript

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.

advancedjavascript

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.

advancedjavascript

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.

advancedjavascript

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.

basicjavascript

Container With Most Water

Use two pointers moving inward from both ends to find the maximum water area between pairs of vertical lines.

intermediatejavascript

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.

intermediatejavascript

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.

advancedjavascript

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.

intermediatepython

Combination Sum with Backtracking

Generate every unique combination of candidates that sums to a target, allowing unlimited reuse of each candidate.

intermediatepython

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.

intermediatepython

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.

basicpython

K Largest Elements with heapq

Use Python's heapq.nlargest to return the k largest values of a list in descending order, including duplicates.

intermediatepython

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.

basicpython

Sieve of Eratosthenes

Generate every prime up to n with the sieve of Eratosthenes, marking multiples starting from each prime's square.

intermediatepython

Minimum Size Subarray Sum

Use a growing and shrinking window to find the shortest contiguous subarray whose sum reaches a target value.

intermediatepython

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.

intermediatepython

Word Dictionary with a Prefix Trie

Implement a trie supporting word insertion, exact lookup, and prefix checks, then replay search and prefix queries.

intermediatepython

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.

advancedpython

Asyncio Rate Limiting with Semaphore

Limit concurrent async jobs with asyncio.Semaphore, keep results in input order, and track the observed peak concurrency.

advancedpython

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.

basicpython

Aggregate CSV Rows by Category

Parse CSV text with csv.DictReader, validate amounts, and return category totals ordered by amount descending then name.

advancedpython

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.

intermediatepython

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.

intermediatepython

Stream and Filter JSON Lines

Parse newline-delimited JSON events, keep purchases above a threshold, and count malformed lines without aborting the stream.

intermediatepython

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.

intermediatepython

Merge Overlapping Intervals (Python)

Sort intervals by start and merge overlapping or touching ranges into a minimal disjoint set in linear time after sorting.

advancedpython

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.

intermediatepython

Retry Decorator with Exception Filtering

Build a decorator that retries only selected exceptions, applies exponential backoff, and re-raises the final failure unchanged.

intermediatepython

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.

intermediatepython

Context Manager That Guarantees Cleanup

Implement a transaction context manager that commits on success, rolls back on exceptions, and always marks the resource closed.

intermediatepython

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.

intermediatepython

Thread Pool Fan-Out with ThreadPoolExecutor

Run independent I/O-bound jobs concurrently with ThreadPoolExecutor, preserve input order, and surface the first worker exception.

advancedpython

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.

intermediatepython

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.

advancedsql

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.

intermediatesql

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.

basicsql

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.

intermediatesql

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.

intermediatesql

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.

basicsql

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.

intermediatesql

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.

advancedsql

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.

intermediatesql

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.

advancedsql

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.

basictypescript

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.

advancedtypescript

Edit Distance with Rolling DP

Compute the Levenshtein distance between two strings using a one-dimensional dynamic programming row that is updated in place.

intermediatetypescript

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.

basictypescript

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.

advancedtypescript

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.

advancedtypescript

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.

advancedtypescript

Generic Priority Queue with a Comparator

Implement a typed binary min-heap priority queue that accepts any element type and a custom comparison function.

intermediatetypescript

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.

intermediatetypescript

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.

basictypescript

Spiral Matrix Traversal

Walk an m by n matrix in clockwise spiral order by shrinking top, bottom, left, and right boundaries after each side.

intermediatetypescript

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.

intermediatetypescript

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.

advancedtypescript

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.

intermediatetypescript

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.

intermediatetypescript

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.

intermediatetypescript

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.

intermediatetypescript

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.

advancedtypescript

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.

intermediatetypescript

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.

advancedtypescript

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.

advancedtypescript

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.

advancedtypescript

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.

intermediatebash

Associative Array Counting

Use bash associative arrays to count occurrences of items in a list with proper key-value storage and iteration patterns.

basicbash

Conditional Tests and File Checks

Use bash test operators for file existence, string comparison, and numeric conditions.

basicbash

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.

basicbash

Function Arguments and Return

Write bash functions that accept arguments and return values via echo and exit codes.

intermediatebash

Getopts for CLI Options

Parse command-line options and arguments using bash getopts built-in with comprehensive examples and best practices for production use.

basicbash

Heredoc for Multiline Templates

Use bash heredoc syntax for generating multiline text files and configuration templates.

intermediatebash

Parallel Job Execution

Run multiple bash commands in parallel using background jobs and wait for completion.

basicbash

Pipeline Text Filtering

Use bash pipelines with grep, sort, and uniq to filter and analyze text data streams.

basicbash

String Manipulation Patterns

Use bash parameter expansion for substring extraction, replacement, and case conversion.

intermediatebash

Trap for Cleanup on Exit

Use bash trap to run cleanup functions on script exit, interrupt, or error signals.

basiccss

Keyframe Animations

Create smooth CSS animations using keyframes with timing functions and delays.

advancedcss

Container Queries for Components

Use CSS container queries for responsive components that adapt to their container size.

intermediatecss

CSS Custom Properties Theming

Use CSS custom properties for dynamic theming with runtime variable updates.

basiccss

Flexbox Navigation Bar

Create a responsive navigation bar using CSS flexbox with space-between alignment.

intermediatecss

Fluid Typography with Clamp

Use CSS clamp function for fluid typography that scales smoothly between viewport sizes.

intermediatecss

CSS Grid Dashboard Layout

Create a dashboard layout using CSS Grid with named template areas for responsive panels.

basiccss

Pseudo-Elements for Decorations

Use CSS pseudo-elements ::before and ::after for decorative content and effects.

basiccss

Media Query Breakpoints

Use CSS media queries for responsive design with mobile-first breakpoint strategy.

intermediatecss

Scroll Snap for Carousels

Use CSS scroll-snap properties for touch-friendly carousel and gallery scrolling.

basiccss

Smooth CSS Transitions

Use CSS transitions for smooth state changes with custom timing and properties.

intermediatego

Go Channel Communication

Use Go channels for safe communication between goroutines with buffering and direction restrictions.

intermediatego

Channel Select Multiplexing

Use Go select statement to multiplex across multiple channels for concurrent communication.

advancedgo

Go Concurrent Pipeline

Build a multi-stage concurrent pipeline in Go using channels and goroutines for streaming data processing.

advancedgo

Go Context Cancellation

Use Go context package for cancellation propagation, timeouts, and request-scoped values across goroutines.

intermediatego

Context with Timeout

Use context.WithTimeout to cancel long-running operations and prevent resource leaks.

basicgo

Defer for Resource Cleanup

Use Go defer statements to ensure resource cleanup runs even when errors occur.

basicgo

Go Error Handling

Practice Go error handling patterns including checking errors, wrapping, and custom error types.

basicgo

Error Wrapping and Unwrapping

Use Go 1.13+ error wrapping with fmt.Errorf and errors.Is for contextual error handling.

advancedgo

Go Generic Constraints

Use Go generics with custom type constraints to implement type-safe algorithms for ordered and numeric types.

basicgo

Generic Min Function

Use Go 1.18+ generics to implement a type-safe min function for any ordered type.