Examples
Programming examples
Search short, complete examples by language and topic.
Python Variables
Store and reuse values with clear names.
Python arithmetic and operators
Calculate totals and distinguish division from floor division.
Python Lists
Keep ordered values together.
Python Functions
Package reusable behavior.
Python decisions and boundaries
Choose one branch with if, elif, and else.
Python loops and accumulators
Build a total one iteration at a time.
Python while loops and digit processing
Repeat until a changing condition becomes false.
Python nested loops and matrices
Visit every cell of a rectangular matrix.
Python strings and palindrome checks
Normalize text before comparing characters.
Python conversion and input validation
Convert text safely and handle invalid input.
Python recursion and factorial
Separate a base case from a smaller recursive problem.
Python files and context managers
Write and read a UTF-8 text file with automatic cleanup.
Python classes and objects
Give each object its own state and methods.
Python encapsulation and properties
Keep validation next to the state it protects.
Python inheritance and polymorphism
Call overridden behavior through a common interface.
Python abstraction with abstract classes
Specify required behavior while leaving implementation to subclasses.
Python composition and object relationships
Build behavior by containing another object.
Python algorithm complexity
Compare linear work with quadratic work by counting operations.
Python sets and tuples
Choose uniqueness or immutable grouping to fit the problem.
Python linear search
Find the first matching element without assuming sorted input.
Python binary search
Halve a sorted search interval after each comparison.
Python bubble sort
Move the largest remaining item to the end with adjacent swaps.
Python selection sort
Select the smallest remaining value for each position.
Python insertion sort
Grow a sorted prefix by shifting larger elements.
Python merge sort
Sort halves recursively and merge them in order.
Python quicksort and partitioning
Partition around a pivot, then sort smaller subproblems.
Python stacks and balanced parentheses
Use last-in, first-out storage to match nested parentheses.
Python queues with deque
Process work in first-in, first-out order.
Python dictionaries and frequency counting
Count repeated values using key-value lookup.
Python singly linked lists
Follow node references and insert at the head.
Python binary search trees
Insert ordered keys and traverse them in sorted order.
Python heaps and priority queues
Remove the smallest priority efficiently.
Python graphs and breadth-first search
Visit reachable vertices level by level without revisiting cycles.
Python depth-first search
Explore one branch fully before returning to alternatives.
Python Dijkstra shortest paths
Relax nonnegative weighted edges using a priority queue.
Python dynamic programming
Reuse earlier results instead of recomputing overlapping subproblems.
Python backtracking and subsets
Choose, recurse, and undo to explore a decision tree.
Growth rates and asymptotic notation
Count operations to see how logarithmic, linear, and quadratic work grow with input size.
Recurrences and the master theorem
Describe divide-and-conquer cost with a recurrence and check it against its closed form.
Amortized analysis
Show that an occasional expensive step still gives constant average cost per operation.
Best, worst, and average case
Measure comparisons for lucky, unlucky, and typical inputs to the same algorithm.
Correctness with loop invariants
Prove that insertion sort is correct by checking an invariant before every iteration.
Time–space trade-offs with memoization
Spend memory on a cache to turn exponential recursion into linear work.
The relational model and constraints
Define tables with keys and constraints so the database rejects invalid data.
Querying with SELECT, GROUP BY, and HAVING
Filter rows, group them, filter the groups, and sort the results.
Joins: combining tables
Match rows across tables with INNER and LEFT joins and keep rows that have no match.
Normalization and update anomalies
Split a redundant table so each fact is stored once and updates cannot contradict themselves.
Transactions and ACID
Group updates so they all happen or none do, and roll back when a rule fails.
Indexes and query plans
See how an index changes a table scan into a search by reading the query plan.
CPU scheduling: FCFS and shortest job first
Compare average waiting time when the scheduler runs jobs in arrival order or by shortest burst.
Round-robin scheduling and the time quantum
Share the CPU fairly by running each job for at most one quantum, then rotating the queue.
Page replacement: FIFO, LRU, and optimal
Count page faults for three replacement policies and see Belady's anomaly with FIFO.
Deadlock avoidance with the banker's algorithm
Grant a resource request only if the resulting state is safe: every process can still finish.
Synchronization: locks and the bounded buffer
Protect shared data with a lock and coordinate a producer and consumer with a blocking queue.
Virtual memory: address translation with a page table
Split a virtual address into page number and offset and map it to a physical frame.
Protocol layers and encapsulation
Wrap data in transport, network, and link headers on the way down and unwrap it on the way up.
IP addressing, CIDR, and subnets
Read a prefix length, count addresses and usable hosts, and split a network into subnets.
TCP sockets: a loopback echo server
Open a listening socket, connect a client, and exchange bytes over a reliable stream.
UDP datagrams
Send independent datagrams with no connection and see how UDP differs from TCP.
HTTP messages: requests, responses, and status codes
Read the text structure of an HTTP/1.1 request and response, and parse a response by hand.
Forwarding with longest-prefix match
Choose the next hop by finding the most specific route that matches a destination address.
Unit testing with unittest
Write small automated tests that check normal behavior, boundaries, and error handling.
Refactoring safely with tests
Restructure code without changing its behavior, and prove that behavior is unchanged.
SOLID design: depend on abstractions
Pass behavior into a class so it can be extended without being edited.
The observer pattern and an event bus
Let a publisher notify many subscribers without knowing who they are.
How version control works: commits, history, and merge bases
Model a commit graph as hashes and parents, and find the common ancestor used to merge branches.
Contracts, invariants, and exceptions
State what a function requires and guarantees, and fail fast with clear errors.
Cryptographic hashing and integrity
Compute SHA-256 digests and see why a one-character change produces a completely different hash.
Storing passwords safely
Hash passwords with a unique salt and a deliberately slow function, then verify in constant time.
Message authentication with HMAC
Attach a keyed tag to a message so that tampering is detected by anyone who holds the key.
The one-time pad and why keys must never be reused
Use XOR as a cipher and see how reusing a key leaks the relationship between two messages.
SQL injection and parameterized queries
See how string-built queries let input change the query, and how placeholders prevent it.
Secure randomness for tokens and secrets
Generate unpredictable tokens with the secrets module, and see why the random module is not for security.
Concurrency with thread pools for waiting work
Overlap tasks that mostly wait, such as network or disk requests, and keep results in order.
Parallelism with processes for CPU-bound work
Split heavy computation across worker processes that run on separate cores.
Speed-up limits: Amdahl's and Gustafson's laws
Compute how much faster a program can get when only part of it runs in parallel.
MapReduce: word count in three phases
Express a computation as map, shuffle, and reduce steps that can run on many machines.
Logical time: Lamport clocks
Order events across machines without a shared clock by counting events and message receipts.
Replication and quorums
Read and write a majority of replicas so that every read overlaps the latest write.
Intelligent agents and environments
Model an agent that perceives its environment and chooses actions, using a simple reflex vacuum cleaner.
State-space search: the water jug problem
Formulate a puzzle as states, actions, and a goal, and find a shortest solution with breadth-first search.
A* search with an admissible heuristic
Guide search toward the goal with a heuristic and compare how many cells it expands against uniform-cost search.
Adversarial search: minimax and alpha-beta pruning
Choose moves in a two-player game and prune branches that cannot change the result.
Constraint satisfaction: coloring a map
Assign values to variables so that every constraint holds, using backtracking search.
Local search: hill climbing for the 8-queens puzzle
Improve a complete state step by step, and use restarts to escape local optima.
Propositional logic and entailment by model checking
Decide whether a knowledge base entails a conclusion by checking every truth assignment.
Forward chaining with definite clauses
Derive new facts from if-then rules until the query is proved or nothing new follows.
Resolution and proof by refutation
Prove a conclusion by adding its negation to the clauses and deriving the empty clause.
Semantic networks, inheritance, and default reasoning
Represent categories and properties as a network, and let specific knowledge override general defaults.
First-order unification
Find the substitution that makes two logical terms identical, including the occurs check.
Reasoning under uncertainty: Bayes' rule
Update beliefs with Bayes' rule and compute a posterior from a small Bayesian network by enumeration.
Evaluating classifiers: accuracy, precision, recall, F1
Build a confusion matrix and see why accuracy alone can be misleading for rare classes.
Linear regression with gradient descent
Fit a line by repeatedly stepping the parameters downhill on the squared error, and check it against the closed form.
Logistic regression for classification
Turn a linear score into a probability with the sigmoid and train it by gradient descent on log loss.
k-nearest neighbors and feature scaling
Classify by distance to stored examples, and see how an unscaled feature can dominate the result.
Decision trees: entropy and information gain
Choose the feature that best splits the data by measuring how much it reduces uncertainty.
k-means clustering
Group unlabelled points by alternating between assigning points to centroids and moving the centroids.
Overfitting and cross-validation
Compare training accuracy with leave-one-out validation accuracy to choose k and detect memorization.
The perceptron and linear separability
Train a single artificial neuron with the perceptron rule, and see why it cannot learn XOR.
Activation functions and softmax
Compare sigmoid, tanh, and ReLU, and compute a numerically stable softmax.
Multilayer networks: a forward pass that computes XOR
Combine two layers of neurons with hand-chosen weights to compute XOR, which one neuron cannot.
Backpropagation: learning XOR by gradient descent
Compute gradients with the chain rule, verify them numerically, and train a small network on XOR.
Cross-entropy loss and the softmax gradient
See why classification networks use cross-entropy, and verify its simple gradient numerically.
Convolutional networks: output shapes and parameter counts
Compute how convolution and pooling change the size of an image, and why sharing weights saves parameters.
Regularization: weight decay and dropout
Shrink weights with an L2 penalty, and see why inverted dropout keeps the expected activation unchanged.
Images as arrays of pixels
Represent a grayscale image as rows of numbers, convert color to gray, and adjust brightness with clipping.
Filtering images with convolution
Slide a small kernel over an image to blur it, and compute the valid output size.
Edge detection with the Sobel operator
Estimate intensity gradients with two kernels and combine them into edge strength and direction.
Thresholding with Otsu's method
Pick a threshold automatically by maximizing the separation between dark and bright pixel groups.
Connected-component labeling
Find and number separate blobs in a binary image with a flood fill, and measure their sizes.
Template matching with sum of squared differences
Find where a small pattern occurs in an image by sliding it over every position and scoring the match.
C Variables
Declare typed values.
C Arrays
Store a fixed sequence.
C Pointers
Work with memory addresses.
C conditions, loops, and totals
Combine a counted loop with an even-number condition.
C strings and null terminators
Traverse characters without reading beyond the string.
C functions and pointer parameters
Modify caller-owned values through valid addresses.
C structures and records
Group related fields into a typed record.
C dynamic memory and ownership
Allocate, check, use, and free a heap buffer.
C reading and writing text files
Write lines to a file with fprintf, read them back with fgets, and parse each line with sscanf.
C bit manipulation and flags
Set, clear, test, and toggle bits with &, |, ^, ~, and shifts, and count set bits.
C two-dimensional arrays
Store a matrix, transpose it, and multiply it with another one.
C macros versus inline functions
See how a macro evaluates its arguments more than once and why a function is safer.
C array search with explicit length
Search only within the supplied array bounds.
C linked nodes and traversal
Connect records with pointers and follow a chain.
C array-based stacks and circular queues
Build a fixed-capacity stack and a queue that wraps around the end of its array.
C binary search and the standard bsearch
Find a value in a sorted array in logarithmic time, by hand and with the library function.
C sorting: bubble sort versus quicksort
Implement two sorts, count their comparisons, and see why O(n log n) beats O(n²).
C binary search trees with malloc and free
Allocate tree nodes dynamically, traverse them in order, and release every node.
C string algorithms
Write strlen and strcmp by hand, check palindromes, and count occurrences with strstr.
C dynamic programming: longest common subsequence
Fill a table of subproblem answers to find the longest sequence that two strings share.
C: best, worst, and average case of linear search
Count comparisons to see how the cost of one algorithm depends on the input it receives.
C: amortized cost of a growing array
Double the capacity of a malloc'd array when it fills, and count the copies made.
C: a hash index with chaining
Store keys in buckets of linked lists and see how collisions lengthen a lookup.
C: a sorted index and range queries with lower_bound
Use binary search on a sorted array to find the first key at or above a value and read a range from there.
C: simulating round-robin scheduling
Give each job a fixed time slice in turn and compute the turnaround time of each.
C: protecting a shared counter with a POSIX mutex
Run two threads that increment one counter and use pthread_mutex_lock so no update is lost.
C: the CRC-32 frame check sequence
Compute the cyclic redundancy check used by Ethernet and detect a single flipped bit.
C: network, broadcast, and host count of a CIDR block
Use shifts and masks on a 32-bit address to describe a subnet.
C: unit testing with a small macro
Report which checks pass and fail by printing the text of each expression.
C: the strategy pattern with function pointers
Choose behaviour at run time by passing a function to qsort, without changing the sorting code.
C: preventing buffer overflows with snprintf
Copy text into a fixed buffer without writing past its end, and detect truncation.
C: validating numeric input with strtol
Accept only text that is entirely a number in the allowed range, and reject everything else.
C: why a one-time pad key must never be reused
XOR two messages with the same key and show that the key cancels out and leaks information.
C: splitting a sum across threads without sharing
Give each thread its own range and result slot, then combine the results after joining.
C: the speed-up limit of Amdahl's law
Compute the best possible speed-up for a program in which only part of the work can run in parallel.
C: breadth-first search on a grid with an array queue
Find the length of the shortest path through a maze using a queue stored in a plain array.
C: game search with negamax and a memo table
Solve a take-away game and count how many positions memoization saves.
C: forward chaining with bit sets
Store facts as bits of an integer and apply if-then rules with bitwise operations.
C: resolution refutation with clauses as bit masks
Represent each clause by two masks, one for positive and one for negative literals, and resolve until a contradiction appears.
C: linear regression with gradient descent
Fit y = w·x + b by repeatedly stepping the parameters against the gradient of the mean squared error.
C: k-nearest-neighbors classification
Sort training points by distance to a query and let the k closest vote.
C: training a perceptron until it makes no mistakes
Use integer weights and the perceptron rule to learn the AND function.
C: softmax and why the largest score is subtracted
Convert scores to probabilities and show that the naive formula overflows for large scores.
C: smoothing noise with a box-blur convolution
Average each 3×3 neighbourhood of a small image to reduce an isolated bright pixel.
C: grayscale histogram and a global threshold
Count how many pixels have each brightness level and separate dark from bright pixels at the mean.
C++ Basics
Write and run a first program.
C++ conditions and range loops
Filter a sequence while accumulating a result.
C++ functions and references
Use a reference parameter to update a caller's value.
C++ recursive factorial
Trace recursive calls and their return values.
C++ strings and string streams
Use std::string, parse text with getline and istringstream, and convert between text and numbers.
C++ references, const, and auto
Pass large objects without copying, protect them with const, and let the compiler deduce types.
C++ lambdas and the standard algorithms
Sort, search, count, transform, and remove elements with algorithms and small anonymous functions.
C++ Classes
Group data and behavior.
C++ constructors and encapsulation
Initialize private state and expose a controlled interface.
C++ abstract classes and virtual dispatch
Invoke derived behavior through a base reference.
C++ composition and RAII
Let owned members manage their resources automatically.
C++ function templates
Reuse one type-checked algorithm for different types.
C++ inheritance and virtual functions
Call the right method through a base-class pointer, and see what slicing does.
C++ operator overloading
Give a Vec2 class natural arithmetic, comparison, and output operators.
C++ smart pointers and ownership
Use unique_ptr for single ownership, shared_ptr for shared ownership, and weak_ptr to observe.
C++ vectors and iterator invalidation
Grow a dynamic array and use checked access.
C++ binary search with lower_bound
Find an insertion position and check whether it is a match.
C++ stack and queue adapters
Compare LIFO and FIFO removal on the same values.
C++ ordered maps and frequencies
Count keys and traverse them in sorted order.
C++ linked lists with unique ownership
Build a node chain with automatic destruction.
C++ sorting: insertion sort, merge sort, and std::stable_sort
Write two sorts by hand and sort records with a comparator, keeping equal items in order.
C++ singly linked list with unique_ptr
Own each node with a unique_ptr, push at the front, reverse the list, and let destructors do the cleanup.
C++ binary search tree traversals
Insert values into a BST and visit them depth-first and level by level.
C++ priority_queue and the top-k pattern
Use a binary heap to get the smallest element quickly, and keep the k largest values of a stream.
C++ graphs: BFS, DFS, and connected components
Store a graph as adjacency lists, visit it breadth-first and depth-first, and count its components.
C++: best, worst, and average case of linear search
Count comparisons to see that one algorithm can have different costs on different inputs.
C++: amortized cost of a growing array
Count the copies made by a doubling array to see why push_back is amortized constant time.
C++: a hash join with unordered_map
Join two tables by building a hash table on one and probing it with each row of the other.
C++: an ordered index with std::map
Answer range and nearest-key queries with lower_bound and upper_bound.
C++: page replacement with FIFO and LRU
Count page faults for two replacement policies and see Belady's anomaly.
C++: protecting shared data with std::mutex
Run two threads that increment one counter and use a lock to keep every update.
C++: the Internet checksum
Compute the 16-bit ones'-complement checksum used by IP, TCP, and UDP, and use it to detect corruption.
C++: forwarding with longest-prefix match
Pick the most specific route that matches a destination address, as a router does.
C++: a small unit-test harness
Check results and expected exceptions with a macro and a template, and report failures.
C++: the observer pattern with std::function
Notify any number of listeners without the publisher knowing what they do.
C++: preventing buffer overflows with bounds checks
Reject writes that do not fit in a buffer and use at() so out-of-range reads fail safely.
C++: validating untrusted input with std::from_chars
Parse a port number strictly and reject anything that is not exactly a number in range.
C++: splitting a sum across std::async tasks
Run two halves of a computation concurrently and combine the results with futures.
C++: lock-free counting with std::atomic
Increment a shared counter from four threads without a mutex.
C++: A* search with a Manhattan-distance heuristic
Guide a shortest-path search with an estimate of the remaining distance.
C++: minimax with alpha-beta pruning
Search a game tree and skip branches that cannot change the result.
C++: entailment by enumerating models
Test whether a knowledge base entails a query by checking every truth assignment.
C++: backward chaining from a goal
Prove a goal by finding a rule that concludes it and then proving that rule's conditions.
C++: linear regression with gradient descent
Fit y = w·x + b by repeatedly moving the parameters against the gradient of the mean squared error.
C++: k-means clustering
Group unlabeled points by alternating between assigning points to centers and moving centers to the mean.
C++: a perceptron learns OR but not XOR
Train the same neuron on two gates and compare the accuracy it can reach.
C++: stable softmax and cross-entropy loss
Turn raw scores into probabilities, measure the loss, and avoid overflow.
C++: convolution with zero padding
Apply a Laplacian kernel so the output has the same size as the input and responds to a single bright pixel.
C++: grayscale conversion and thresholding
Convert color pixels to brightness with luminance weights and split them into foreground and background.
Java Basics
Start with a class and main method.
Java conditions, arrays, and loops
Count values that satisfy a boundary condition.
Java methods and exception handling
Separate conversion errors from valid numeric values.
Java recursion and bounded factorial
Use a base case and validate the representable range.
Java variables, types, and casting
Declare typed variables and understand integer division, overflow, and conversions.
Java arrays and strings
Work with fixed-size arrays, common String methods, and the difference between == and equals.
Java method overloading, varargs, and pass by value
Declare several methods with the same name and see what a method can and cannot change.
Java constructors and encapsulation
Initialize private fields and validate changes through methods.
Java inheritance and method overriding
Use a superclass reference to call subclass behavior.
Java interfaces and composition
Depend on a contract and inject a collaborating object.
Java abstract classes and enums
Define a shared base with an abstract method, and a fixed set of constants with fields.
Java generics and bounded types
Write one class and one method that work for many types while the compiler checks them.
Java equals, hashCode, and toString
Define when two objects are equal so that they work correctly in sets and maps.
Java ArrayList and generics
Use a resizable, type-checked sequence.
Java binary search and interval bounds
Implement logarithmic search on an ascending array.
Java stacks and balanced brackets
Use a stack to check that brackets are properly nested.
Java ArrayDeque as a queue
Choose queue operations with explicit empty-queue behavior.
Java maps, sets, and duplicate counting
Track counts and distinct values with separate collection roles.
Java singly linked lists
Build a list of nodes by hand, insert at the front and the back, and reverse it.
Java binary search trees
Insert values into a tree that keeps smaller values on the left, and traverse it in sorted order.
Java sorting: insertion sort, merge sort, and comparators
Implement two sorts by hand and sort objects with a Comparator.
Java priority queues and heaps
Always remove the smallest (or largest) item, and find the k largest values.
Java: counting operations to see growth rates
Count loop iterations instead of timing them to compare linear, quadratic, and logarithmic growth.
Java: amortized cost of a growing array
Show that doubling a backing array makes append cost O(1) on average even though some appends copy everything.
Java: a hash join and why it beats a nested loop
Join two collections by building a hash table on one side and probing it with the other.
Java: an ordered index with TreeMap
Use a sorted map the way a database uses an ordered index to answer range and nearest-key queries.
Java: simulating round-robin CPU scheduling
Rotate jobs through a ready queue with a fixed time slice and record when each one finishes.
Java: mutual exclusion with synchronized
Protect a shared counter from lost updates when two threads increment it.
Java: a TCP echo server on the loopback interface
Open a server socket on an ephemeral port and connect to it with a client socket in the same program.
Java: IPv4 addresses, masks, and CIDR blocks
Compute the network address, broadcast address, and host count of a subnet with bitwise operations.
Java: testing a method with a tiny test runner
Check normal cases, boundaries, and error cases, and report which ones pass.
Java: strategy and observer with interfaces and lambdas
Swap behavior behind an interface and notify listeners without coupling the sender to them.
Java: SHA-256 hashing for integrity
Compute a SHA-256 digest with MessageDigest and see that a tiny change produces a completely different value.
Java: storing passwords with a salt and PBKDF2
Derive a password hash with a random salt and many iterations, then verify a login attempt.
Java: splitting work across a thread pool
Divide a sum into chunks, run them on an ExecutorService, and combine the Future results.
Java: parallel streams and CompletableFuture
Count items with a parallel stream and combine two asynchronous results.
Java: breadth-first search for a shortest path
Search a grid with a queue to find the fewest moves from the start to the goal around walls.
Java: game-tree search with minimax (negamax)
Search every move in a take-away game to find which positions are winning for the player to move.
Java: propositional entailment by model checking
Enumerate every truth assignment to decide whether a knowledge base entails a query.
Java: forward chaining with if-then rules
Repeatedly apply rules whose conditions are known until no new facts can be derived.
Java: linear regression with gradient descent
Fit a straight line to data by repeatedly stepping the weights against the gradient of the squared error.
Java: k-nearest-neighbors classification
Classify a point by letting its k closest training points vote.
Java: training a perceptron to learn AND
Update the weights of a single neuron with the perceptron rule until it classifies all four inputs correctly.
Java: a two-layer network that computes XOR
Combine two hidden neurons so that a network solves the problem a single perceptron cannot.
Java: filtering an image with a convolution kernel
Slide a 3×3 averaging kernel over a small grayscale image to smooth it.
Java: finding edges with the Sobel operator
Estimate the horizontal intensity change at each pixel and mark strong edges.
JavaScript Variables
Use const and let for values.
JavaScript Functions
Write reusable logic.
JavaScript conditions and array loops
Filter values with strict comparisons and accumulate a total.
JavaScript map, filter, and reduce
Build a transformation pipeline without mutating the source.
JavaScript types, equality, and coercion
Know the primitive types, why === is safer than ==, and which values count as false.
JavaScript closures and scope
Use a function that remembers its surrounding variables, and see why let fixes the classic loop bug.
JavaScript destructuring, spread, and rest
Unpack objects and arrays into variables, copy with spread, and collect arguments with rest.
JavaScript string methods and regular expressions
Split, pad, replace, and extract parts of text with strings and regular expressions.
JavaScript promises, async, and await
Write asynchronous code that reads like synchronous code, and handle errors with try and catch.
JavaScript classes and private fields
Protect instance state with a private class field.
JavaScript inheritance and overriding
Reuse initialization and specialize instance behavior.
JavaScript prototypes and class inheritance
See that classes are built on prototype chains, and extend one constructor from another.
JavaScript private fields, getters, and static members
Hide state with #private fields, expose it through a getter, and keep a counter on the class itself.
JavaScript binary search
Search a sorted numeric array with a shrinking interval.
JavaScript Map and Set
Count values and identify distinct entries.
JavaScript linked lists and iterators
Build a singly linked list class that can be looped over with for...of.
JavaScript stacks and queues
Use an array as a stack, and write a queue that does not shift the whole array on every removal.
JavaScript sorting and the default sort pitfall
Learn why [10, 9, 1].sort() is wrong, sort with comparators, and write a merge sort.
JavaScript binary search trees with a generator
Insert values, search, and produce the sorted order lazily with a recursive generator.
JavaScript graphs: BFS, DFS, and path existence
Store a graph as a Map of neighbour lists and search it breadth-first and depth-first.
JavaScript: memoization trades memory for time
Count the calls made by a naive recursive Fibonacci and a memoized one.
JavaScript: counting the steps of binary search
Show that searching a sorted array of 1000 items takes at most about ten comparisons.
JavaScript: an index turns a scan into a lookup
Compare scanning an array for a row with looking it up in a Map keyed by id.
JavaScript: GROUP BY and HAVING with Map
Total a column per group, keep the groups that pass a condition, and sort them.
JavaScript: the event loop as a cooperative scheduler
Predict the order in which synchronous code, nextTick, promises, and timers run in Node.js.
JavaScript: LRU replacement with a Map
Use Map's insertion order to evict the least recently used page and count page faults.
JavaScript: an HTTP server and client on the loopback interface
Start a Node.js HTTP server on a free port and request it with fetch to see status codes.
JavaScript: a TCP echo server with the net module
Send a line through a TCP socket and print the server's reply.
JavaScript: unit tests with node:assert
Write small tests with assertions, including checks that bad input throws the right error.
JavaScript: the observer pattern with EventEmitter
Let several listeners react to the same event without the emitter knowing about them.
JavaScript: SHA-256 hashing and HMAC with node:crypto
Hash a message, authenticate it with a secret key, and compare tags in constant time.
JavaScript: storing passwords with scrypt and a salt
Derive a memory-hard hash from a password and a random salt, then verify a login attempt.
JavaScript: preventing XSS by escaping output
Turn special HTML characters into entities so user text is shown as text, never run as markup.
JavaScript: concurrency without parallelism
See how async functions interleave on a single thread and finish together under Promise.all.
JavaScript: real parallelism with worker threads
Split an array between two worker threads and add their partial results.
JavaScript: breadth-first search for the fewest steps
Find a shortest path in an unweighted graph by exploring it layer by layer.
JavaScript: constraint satisfaction by backtracking
Color a map so that neighbouring regions differ, counting every valid coloring.
JavaScript: querying facts stored as triples
Represent knowledge as subject–predicate–object triples and answer queries with variables.
JavaScript: proof by resolution refutation
Show that a knowledge base entails a query by deriving a contradiction from the knowledge base plus the negated query.
JavaScript: fitting a line with least squares
Compute the slope, intercept, and R² of the best-fit line in closed form.
JavaScript: a naive Bayes text classifier
Classify short messages as spam or ham from word counts with Laplace smoothing.
JavaScript: a forward pass through two dense layers
Multiply by weight matrices, add biases, apply ReLU, and finish with softmax probabilities.
JavaScript: checking a gradient numerically
Compare a hand-derived gradient with a finite-difference estimate, the standard test for backpropagation code.
JavaScript: RGBA pixel arrays and Uint8ClampedArray
Convert pixels stored the way a canvas stores them to grayscale and see how clamping works.
JavaScript: a sharpen filter and why clamping matters
Apply a sharpening kernel to a step edge and see the overshoot clamped to the valid range.
TypeScript Types
Describe values before runtime.
TypeScript Union Types and Narrowing
Accept more than one type and narrow it safely with typeof.
TypeScript literal types and as const
Build a union of allowed strings from an object or array and make switch statements exhaustive.
TypeScript unknown and user-defined type guards
Validate parsed JSON at run time and let the compiler trust the result only after the check.
TypeScript tuples, readonly, and optional chaining
Return fixed-shape pairs, protect arrays from change, and read nested optional values safely.
TypeScript Interfaces
Describe the shape of an object, including optional properties.
TypeScript abstract classes and access modifiers
Use private, protected, readonly, and abstract to describe what subclasses and outside code may do.
TypeScript Generics
Write one function that keeps the type of whatever it receives.
TypeScript generic stack and queue
Write containers that work for any element type and keep it checked.
TypeScript generic binary search tree
Order any type with a comparator function and collect the values in sorted order.
TypeScript typed comparators and multi-key sorting
Build comparators from a key with keyof, and combine them to sort by several fields.
TypeScript: a typed memoize wrapper
Cache the results of a pure function with a generic higher-order function and count how often the body runs.
TypeScript: type-safe select, where, and orderBy
Write small query helpers whose column names are checked by the compiler with keyof.
TypeScript: a process lifecycle as a typed state machine
Allow only legal transitions between process states and reject the rest.
TypeScript: parsing a raw HTTP request into a typed object
Split the request line, headers, and body of an HTTP/1.1 message and read a query parameter.
TypeScript: explicit errors with a Result type
Return success or failure as a value, and let the compiler force the caller to handle both.
TypeScript: branded types for validated and escaped data
Use the type system so that unvalidated text cannot be passed where a validated value is required.
TypeScript: running async tasks with a concurrency limit
Start at most N tasks at once, collect results in input order, and measure the peak concurrency.
TypeScript: a generic breadth-first search solves the water-jug puzzle
Write the search once for any state type and apply it to two jugs.
TypeScript: propositional formulas as a discriminated union
Represent formulas as trees, evaluate them for any assignment, and test for tautologies.
TypeScript: precision, recall, and F1 from a confusion matrix
Count true and false positives and negatives with a typed interface, then compute the metrics.
TypeScript: composing neural-network layers behind an interface
Build a small network from Dense and Sigmoid layers that share one Layer interface.
TypeScript: a grayscale image class with threshold and flip
Wrap a flat pixel buffer in a class that checks bounds and returns new images from its operations.
HTML Elements
Structure a document with semantic tags.
HTML Forms
Collect input with labelled form controls.
HTML Lists and Tables
Mark up lists and tabular data with the right elements.
HTML Links and Images
Connect pages and show pictures with alternative text.
HTML Semantic Page Layout
Describe the regions of a page with header, nav, main, article, aside, and footer.
HTML Accessibility Basics
Make pages usable with keyboards and screen readers through labels, alt text, and landmarks.
HTML Document Head and Metadata
Set the character encoding, viewport, title, description, and stylesheet for a page.
HTML Responsive Images and Media
Offer different image files for different screens and embed video with a fallback.
HTML Forms: GET versus POST
See what each form method sends over HTTP and when to use it.
HTML Safe Links, Embeds, and Content Security Policy
Limit what linked and embedded content can do with rel, sandbox, and a content security policy.
CSS Selectors
Choose elements and apply styles.
CSS Box Model
Understand content, padding, border, and margin.
CSS Flexbox
Lay out items in a row with spacing and alignment.
CSS Variables and Media Queries
Reuse values and adapt the layout to narrow screens.
CSS Specificity and the Cascade
Predict which rule wins when several rules match the same element.
CSS Grid Layout
Build a two-dimensional page layout with named areas and a responsive card grid.
CSS Transitions, Animations, and Reduced Motion
Animate state changes smoothly and respect users who prefer less motion.
CSS Units and Fluid Typography
Choose relative units and clamp() so text scales with the user's settings and the screen.
SQL SELECT
Read rows from a table.
SQL Aggregates and GROUP BY
Summarize many rows into one row per group.
SQL Joins
Combine rows from two tables that share a key.
SQL INSERT, UPDATE, and DELETE
Add, change, and remove rows, then check the result.
SQL: constraints keep the data valid
Use PRIMARY KEY, NOT NULL, UNIQUE, CHECK, and REFERENCES so the database itself rejects bad rows.
SQL: transactions with COMMIT and ROLLBACK
Move money between two accounts so that both updates happen or neither does.
SQL: normalization removes repeated facts
Split a table that repeats a customer's city on every row into two tables and see why one update is enough.
SQL: subqueries and common table expressions
Compare each row with a group average, and name an intermediate result with WITH.
SQL: window functions for running totals and ranks
Compute a running total and a rank within each group without collapsing the rows.
SQL: views and triggers
Name a reusable query as a view and record price changes automatically with a trigger.
SQL: a unique index and the system catalog
Enforce uniqueness with an index and look up the index in the database's own catalog.
C# Basics
Print a value from a .NET program.
C# Loops
Repeat an action with a for loop.
C# Methods
Package reusable logic in a static method.
C# strings and formatting
Use common string methods, compare text correctly, and format numbers with format specifiers.
C# exceptions, finally, and using
Throw and catch a custom exception, filter by condition, and release resources reliably.
C# nullable values, patterns, and switch expressions
Handle missing values safely and branch on the type and value of an object.
C# Classes and Properties
Protect state with a property that only the class can change.
C# inheritance, virtual, and abstract members
Override behaviour in subclasses and call it through a base-type reference.
C# records, with-expressions, and value semantics
Create immutable data types with value equality, copy them with changes, and compare with structs and classes.
C# delegates, events, and lambdas
Pass behaviour as a value and let objects notify subscribers when something happens.
C# Lists
Grow a collection with List<T> and add its values.
C# Dictionary and HashSet operations
Count words with a dictionary and combine sets with union, intersection, and difference.
C# Stack and Queue: evaluating postfix expressions
Use a stack to evaluate expressions written in reverse Polish notation and a queue for first-in order.
C# sorting, stability, and Array.BinarySearch
Sort arrays and records, keep equal items in order with LINQ, and find insertion points.
C# LRU cache with Dictionary and LinkedList
Combine a hash table and a doubly linked list so that get, put, and eviction all take constant time.
C# generic binary search tree with IEnumerable
Constrain the element type with IComparable<T> and expose the sorted values with yield return.
C#: best and worst case of insertion sort
Count comparisons on sorted, reversed, and mixed input to see how input order changes the cost.
C#: watching List<T> grow geometrically
Observe the capacity of a List<int> as items are added and see that reallocations become rarer.
C#: relational queries with LINQ join and group
Join two collections on a key, sort the result, and aggregate it by group, as SQL does.
C#: an ordered index with SortedSet
Answer range, minimum, maximum, and nearest-value queries on sorted keys.
C#: first-come-first-served versus shortest-job-first
Compare the average waiting time of two scheduling policies for the same set of jobs.
C#: protecting shared state with lock
Start two threads that update one counter and use lock so that no update is lost.
C#: a TCP echo server on the loopback interface
Use TcpListener and TcpClient with async methods to send a line and read the reply.
C#: IPv4 subnets with IPAddress and bit masks
Compute the network and broadcast addresses for a CIDR block and test whether addresses belong to it.
C#: testing values and exceptions with a small harness
Check results, and verify that bad input throws the expected exception type.
C#: dependency injection makes code testable
Pass a dependency in through the constructor so tests can replace it with a fixed one.
C#: message authentication with HMAC-SHA256
Compute a keyed tag so a receiver can detect tampering, and compare tags safely.
C#: password storage with a salt and PBKDF2
Derive a slow salted hash from a password and verify a login attempt in constant time.
C#: running tasks in parallel with Task.WhenAll
Start independent computations as tasks and await all of their results.
C#: Parallel.For with Interlocked
Spread loop iterations over cores and combine results safely with an atomic add.
C#: uniform-cost search with PriorityQueue
Find the cheapest route from a start node to every other node in a weighted graph.
C#: solving tic-tac-toe with minimax
Search the complete game tree and show that perfect play by both sides ends in a draw.
C#: first-order unification
Find a substitution that makes two logical terms identical, including the occurs check.
C#: semantic networks with default reasoning
Inherit properties up an is-a hierarchy and let more specific nodes override defaults.
C#: logistic regression for classification
Predict a probability with the sigmoid function and train the weights by gradient descent.
C#: entropy and information gain for decision trees
Measure how much a feature reduces uncertainty about a label, the criterion used to choose a split.
C#: backpropagation learns XOR
Train a 2-2-1 sigmoid network by gradient descent until it computes XOR.
C#: activation functions and their ranges
Compare sigmoid, tanh, and ReLU on the same inputs.
C#: Sobel gradient magnitude on a diagonal edge
Combine horizontal and vertical Sobel responses into one edge-strength value.
C#: the integral image (summed-area table)
Precompute running sums so that the total of any rectangle takes four lookups.
Go Basics
Print a message from main.
Go Functions and Multiple Return Values
Return more than one value from a function.
Go Loops
Count with the for statement.
Go Structs and Methods
Group fields in a struct and attach behavior to it.
Go Slices
Grow a sequence with append and take a part of it.
Rust Basics
Bind values and print them.
Rust Ownership
Borrow a string without moving it.
Rust Variables, Mutability, and Shadowing
Bindings are immutable by default; mut and shadowing change that.
Rust Enums and match
Model alternatives with an enum and handle each one with match.
Rust Vectors
Store a growable list with Vec and sum it with an iterator.
Kotlin Basics
Use values and string templates.
Kotlin Lists
Process an ordered collection.
Kotlin Functions
Declare typed parameters and a return type.
Kotlin when Expressions
Choose a result from several conditions with when.
Kotlin null safety
Distinguish nullable from non-null types, and use ?., ?:, let, and !! deliberately.
Kotlin collections and higher-order functions
Filter, map, group, sort, and fold lists with lambdas instead of loops.
Kotlin Classes
Declare a class with a primary constructor and private state.
Kotlin data classes and sealed interfaces
Model alternatives with a sealed hierarchy and let the compiler check that every case is handled.
Kotlin object, companion object, and delegation
Create singletons, class-level factories with private constructors, and reuse behaviour by delegating to an interface.
Kotlin sorting and binary search
Sort lists with sorted and sortedBy, and find a value or its insertion point with binarySearch.
Kotlin ArrayDeque as a stack and a queue
Check balanced brackets with a stack and serve items in arrival order with a queue.
Kotlin maps: counting and indexing
Count words with groupingBy and build a lookup map with getOrPut.
Kotlin unit tests with lambdas and runCatching
Write a minimal test function that reports passes and failures, including expected exceptions.
Kotlin SHA-256 and PBKDF2 on the JVM
Hash text with MessageDigest and derive a salted password hash with PBKDF2.
Kotlin threads, AtomicInteger, and an executor
Start threads that update a shared counter safely and split a sum across a thread pool.
Ruby Basics
Store text and print it.
Ruby Arrays
Visit each value in an array.
Ruby Methods and map
Define a method and transform an array with map.
Ruby Classes
Keep state in an instance variable and read it with attr_reader.
Ruby Hashes
Store key-value pairs and iterate over them.
PHP Basics
Print a value from a PHP script.
PHP Arrays
Loop through an indexed array.
PHP Functions
Declare typed parameters and return values.
PHP strings, sprintf, and regular expressions
Format text with sprintf, split and join strings, and match patterns with preg functions.
PHP strict types, match, and the nullsafe operator
Use union types, a match expression, constructor promotion, and ?-> to write safer code.
PHP closures, array functions, and generators
Transform arrays with map, filter, and reduce, capture variables in closures, and produce values lazily with yield.
PHP Classes
Hide a property and change it only through methods.
PHP interfaces, traits, and abstract classes
Share a contract with an interface, share code with a trait, and share both with an abstract base.
PHP Associative Arrays
Map names to values and loop over keys and values.
PHP sorting, usort, and the spaceship operator
Sort arrays by value or by custom rules, and combine several sort keys with <=>.
PHP SPL data structures: stack, queue, and heap
Use the standard SplStack, SplQueue, SplMinHeap, and SplPriorityQueue classes.
PHP unit tests with closures
Write a tiny test runner with named test closures and check normal values and expected errors.
PHP password_hash, password_verify, and hash_hmac
Store passwords with bcrypt through the built-in API and sign messages with HMAC.
PHP preventing XSS with htmlspecialchars
Encode user text before printing it into HTML, and escape for the right context.
Swift Basics
Bind a constant and print it.
Swift Functions and Argument Labels
Use default values and argument labels to make calls readable.
Swift Optionals
Handle values that might be missing with if let.
Swift Structs
Model data with a struct, which is copied when assigned.
Swift Arrays
Grow an array and combine its values with reduce.
Scala Basics
Run a small program with an entry point.
Scala Functions as Values
Define a method and pass it to a higher-order function.
Scala Case Classes and Pattern Matching
Define a data class and take it apart with match.
Scala Collections: map and filter
Transform and filter an immutable List without loops.
Scala Maps and Option
Look up a key without nulls by using Option.
Lua Basics
Store a local value and print it.
Lua Functions
Write a local function that loops over a table and returns a result.
Lua Loops
Count with a numeric for and repeat with while.
Lua Tables
Use one table type as both an array and a record.
Perl Basics
Declare a scalar and print it.
Perl Subroutines
Define a sub that reads its arguments from @_.
Perl regular expressions and text processing
Capture named groups, collect all matches, transliterate characters, and compute replacements with /e.
Perl references and nested data structures
Build hashes of arrays, add to them, and loop over them with references.
Perl file handles on strings and formatted output
Read lines from a string as if from a file, validate each line, and write formatted output to a string.
Perl subroutines, context, and closures
Return different results in list and scalar context, build closures, and write a recursive anonymous function.
Perl packages, bless, and inheritance
Create objects as blessed hashes, override methods in a subclass, and call the parent version.
Perl Arrays
Store a list in an @array and loop over it.
Perl Hashes
Map keys to values and print them in a stable order.
Perl sort blocks and the Schwartzian transform
Sort numbers, hash keys by value, and records by computed keys without recomputing the keys.
Perl stacks, queues, and word frequencies
Use push, pop, shift, and unshift as stack and queue operations, and count items with a hash.
Perl SHA-256 and HMAC with Digest::SHA
Hash messages, authenticate them with a key, and compare tags without leaking timing.