brain

tamnd's digital brain — notes, problems, research

42768 notes

forward

A loop repeats a computation until a condition fails or a fixed iteration count is reached. In automatic differentiation, loops are important because many numerical algorithms...

autodiffbook
Hessian Computation

For a scalar function

autodiffbook
Nilpotent Elements

The defining feature of dual numbers is the existence of a nonzero element whose square vanishes:

autodiffbook
Reverse Computational Graphs

Reverse mode automatic differentiation operates on a computational graph. The forward pass evaluates the graph from inputs to outputs. The reverse pass traverses the same...

autodiffbook
Dual Numbers

Dual numbers give forward mode automatic differentiation a compact algebraic form. Instead of storing a value and a tangent as two unrelated fields, we package them into one...

autodiffbook
Elementary Operations

Automatic differentiation reduces differentiation to a finite collection of elementary operations. Every program, regardless of complexity, is decomposed into primitive...

autodiffbook
Intermediate Variables

Intermediate variables are the named values created between program inputs and program outputs. They make automatic differentiation mechanical.

autodiffbook
Multivariate Calculus

Automatic differentiation is usually applied to functions with many inputs and many outputs. The calculus needed for this setting is multivariate calculus: the study of how a...

autodiffbook
Numerical Differentiation

Numerical differentiation estimates derivatives by evaluating a function at nearby input values. It treats the function as a black box. The method does not need access to the...

autodiffbook
Appendix

ADIFOR, short for Automatic Differentiation of Fortran, is one of the classical source-transformation systems for automatic differentiation. It was designed for numerical...

autodiffbook
Chapter 21. Major AD Systems

ADIFOR, short for Automatic Differentiation of Fortran, is one of the classical source-transformation systems for automatic differentiation. It was designed for numerical...

autodiffbook
Chapter 20. Building an AD Engine

A minimal forward mode automatic differentiation engine has one job: evaluate a program while carrying both a value and its derivative. The engine does not build a graph. It...

autodiffbook
Chapter 19. Theory and Foundations

Automatic differentiation is often described by a simple rule:

autodiffbook
Chapter 18. Advanced Topics

Many programs do not compute their output by applying a fixed sequence of explicit operations. Instead, they define the output as the solution of another problem.

autodiffbook
Chapter 17. Numerical and Systems Concerns

Automatic differentiation computes derivatives by executing arithmetic. On a real machine, arithmetic uses finite precision. This means AD gives the derivative of the...

autodiffbook
Chapter 15. Differentiable Systems Architecture

An end-to-end differentiable pipeline is a system whose final objective can send derivative information backward through every trainable or tunable stage of computation....

autodiffbook
Chapter 14. Scientific Computing Applications

Differential equations are one of the main reasons automatic differentiation matters in scientific computing. Many scientific models are not written as closed-form functions....

autodiffbook
Chapter 13. Optimization and Machine Learning

Gradient descent is the basic optimization procedure behind much of modern machine learning. It is simple enough to state in one line, but rich enough to expose many of the...

autodiffbook
Chapter 12. AD in Modern Programming Languages

Lisp is one of the natural homes of automatic differentiation. It treats programs as data, has a simple expression syntax, and supports macro systems that can transform code...

autodiffbook
Chapter 11. Compiler and Runtime Design

Source transformation is an implementation strategy for automatic differentiation in which a program that computes a function is rewritten into another program that computes...

autodiffbook
Chapter 10. Matrix and Tensor Differentiation

Matrix calculus is the notation and rule system used to differentiate functions whose inputs, outputs, or intermediate values are vectors, matrices, or tensors. Automatic...

autodiffbook
Chapter 9. Differentiation of Control Flow

A conditional is a program construct that chooses one computation among several possible computations. In ordinary code, this is written as if, else, switch, case, pattern...

autodiffbook
Chapter 8. Higher-Order Differentiation

First derivatives describe local rate of change. Second derivatives describe how that rate of change itself changes. In optimization, this is curvature. In dynamics, it is...

autodiffbook
Chapter 7. Dual Numbers and Algebraic Structures

Dual numbers give the cleanest algebraic model of forward mode automatic differentiation. They extend ordinary real numbers with a formal infinitesimal part. Instead of...

autodiffbook
Chapter 6. Reverse Mode Automatic Differentiation

Reverse mode automatic differentiation computes derivatives by propagating sensitivities backward through a computation. In forward mode, each intermediate value carries a...

autodiffbook
Chapter 5. Forward Mode Automatic Differentiation

Forward mode automatic differentiation computes derivatives by carrying two values through a program at the same time: the ordinary value and its tangent. The ordinary value...

autodiffbook
Chapter 4. Core Theory of Automatic Differentiation

Automatic differentiation is built on a simple observation: a complicated derivative can be computed by composing many small local derivatives. Instead of manipulating a full...

autodiffbook
Chapter 3. Programs as Mathematical Objects

A straight-line program is the simplest model of computation used in automatic differentiation. It is a program with a fixed sequence of assignments, no branches, no loops,...

autodiffbook
Chapter 2. Mathematical Foundations

Automatic differentiation begins with a simple object: a function.

autodiffbook
Chapter 1. Introduction

A derivative measures how an output changes when an input changes. That sentence is simple, but it is one of the main ideas behind numerical computing, optimization, machine...

autodiffbook
LeetCode 425: Word Squares

A clear explanation of building all word squares using backtracking with prefix pruning.

leetcodearraystringbacktrackingtriehash-table
LeetCode 475: Heaters

A clear explanation of finding the minimum heater radius by sorting positions and matching each house to its nearest heater.

leetcodearraysortingbinary-searchtwo-pointers
LeetCode 424: Longest Repeating Character Replacement

A clear explanation of finding the longest substring that can become all one letter using a sliding window.

leetcodestringsliding-windowtwo-pointershash-table
LeetCode 474: Ones and Zeroes

A clear explanation of solving the largest subset problem as a two-dimensional 0/1 knapsack over zero and one counts.

leetcodedynamic-programmingknapsackarraystring
LeetCode 423: Reconstruct Original Digits from English

A clear explanation of reconstructing digits from shuffled English words using character frequency counts and unique identifying letters.

leetcodestringhash-tablecounting
LeetCode 473: Matchsticks to Square

A clear explanation of deciding whether matchsticks can form a square using backtracking, sorting, and pruning.

leetcodearraybacktrackingdfsbitmask
LeetCode 500: Keyboard Row

A clear explanation of filtering words that can be typed using only one row of an American keyboard.

leetcodearrayhash-tablestringset
LeetCode 472: Concatenated Words

A clear explanation of finding all words that can be formed by concatenating at least two shorter words from the same list.

leetcodestringdynamic-programmingtriehash-set
LeetCode 450: Delete Node in a BST

Delete a node from a binary search tree while preserving the BST property using recursive search and inorder successor replacement.

leetcodetreebinary-search-treedfsrecursion
LeetCode 400: Nth Digit

A clear explanation of finding the nth digit in the infinite integer sequence using digit groups and arithmetic.

leetcodemathbinary-search
LeetCode 399: Evaluate Division

A clear explanation of solving division equations using graph traversal and weighted edges.

leetcodegraphdfsunion-findweighted-graph
LeetCode 375: Guess Number Higher or Lower II

A clear explanation of finding the minimum guaranteed cost using interval dynamic programming.

leetcodedynamic-programminginterval-dpgame-theoryminimax
LeetCode 499: The Maze III

A clear explanation of finding the shortest rolling-ball path to the hole using Dijkstra with lexicographic tie-breaking.

leetcodegraphdijkstraheapmatrixshortest-path
LeetCode 471: Encode String with Shortest Length

A clear explanation of interval dynamic programming for encoding a string into the shortest k[encoded_string] form.

leetcodestringdynamic-programminginterval-dp
LeetCode 449: Serialize and Deserialize BST

Serialize a binary search tree compactly with preorder traversal and rebuild it using BST value bounds.

leetcodetreebinary-search-treedfsdesignserialization
LeetCode 422: Valid Word Square

A clear explanation of checking whether rows and columns read the same using direct index comparison.

leetcodearraystringmatrixsimulation
LeetCode 398: Random Pick Index

A clear explanation of picking a uniformly random index for a target value using reservoir sampling, with an alternative hash map approach.

leetcodearrayhash-tablemathreservoir-samplingrandomized
LeetCode 374: Guess Number Higher or Lower

A clear explanation of finding the picked number using binary search and the guess API.

leetcodebinary-searchinteractive-api
LeetCode 498: Diagonal Traverse

A clear explanation of returning matrix elements in diagonal zigzag order by grouping cells with the same row plus column index.

leetcodearraymatrixsimulation
LeetCode 373: Find K Pairs with Smallest Sums

A clear explanation of finding the k smallest pair sums from two sorted arrays using a min heap and best-first search.

leetcodeheappriority-queuearraybest-first-search
LeetCode 470: Implement Rand10() Using Rand7()

A clear explanation of generating a uniform random integer from 1 to 10 using only rand7 and rejection sampling.

leetcodemathrandomizedrejection-sampling
LeetCode 448: Find All Numbers Disappeared in an Array

Find all missing numbers from 1 to n in O(n) time using in-place index marking.

leetcodearrayhashingin-place
LeetCode 421: Maximum XOR of Two Numbers in an Array

A clear explanation of finding the maximum XOR of two numbers using greedy bit prefixes.

leetcodearraybit-manipulationgreedytrie
LeetCode 397: Integer Replacement

A clear explanation of reducing an integer to 1 with the fewest operations using greedy bit decisions.

leetcodemathbit-manipulationgreedyrecursion
LeetCode 372: Super Pow

A clear explanation of computing large modular exponentiation using fast power, modular arithmetic, and digit decomposition.

leetcodemathmodular-arithmeticrecursionfast-power
LeetCode 325: Maximum Size Subarray Sum Equals k

A clear explanation of Maximum Size Subarray Sum Equals k using prefix sums and earliest-index hashing.

leetcodearrayhash-tableprefix-sum
LeetCode 324: Wiggle Sort II

A clear explanation of Wiggle Sort II using sorting, median splitting, and virtual indexing.

leetcodearraysortinggreedyquickselect
LeetCode 396: Rotate Function

A clear explanation of maximizing the rotation function using a recurrence instead of simulating every rotation.

leetcodearraymathdynamic-programming
LeetCode 323: Number of Connected Components in an Undirected Graph

A clear explanation of counting connected components using Union-Find and graph traversal.

leetcodegraphunion-finddfsbfs
LeetCode 469: Convex Polygon

A clear explanation of checking whether ordered points form a convex polygon using cross products.

leetcodearraymathgeometry
LeetCode 447: Number of Boomerangs

Count ordered boomerang tuples by fixing each point as the center and grouping other points by squared distance.

leetcodearrayhash-tablemathgeometry
LeetCode 497: Random Point in Non-overlapping Rectangles

A clear explanation of uniformly picking an integer point from non-overlapping rectangles using prefix sums and binary search.

leetcoderandomizedbinary-searchprefix-sumgeometry
LeetCode 420: Strong Password Checker

A clear explanation of checking the minimum edits needed to make a password strong using greedy handling of length, missing character types, and repeated runs.

leetcodestringgreedy
LeetCode 371: Sum of Two Integers

A clear explanation of adding two integers without using plus or minus by using XOR, AND, carry, and a 32-bit mask.

leetcodebit-manipulationmath
LeetCode 350: Intersection of Two Arrays II

A clear explanation of Intersection of Two Arrays II using frequency counting.

leetcodearrayhash-tabletwo-pointerssorting
LeetCode 322: Coin Change

A clear explanation of Coin Change using dynamic programming for minimum coin count.

leetcodedynamic-programmingarray
LeetCode 496: Next Greater Element I

A clear explanation of finding the next greater element using a monotonic decreasing stack and hash map.

leetcodearraystackmonotonic-stackhash-table
LeetCode 419: Battleships in a Board

A clear explanation of counting battleships in a board using one-pass observation without modifying the grid.

leetcodematrixarraycounting
LeetCode 321: Create Maximum Number

A clear explanation of Create Maximum Number using monotonic stacks for subsequences and greedy merging.

leetcodearraygreedymonotonic-stacktwo-pointers
LeetCode 495: Teemo Attacking

A clear explanation of calculating total poisoned duration by merging overlapping attack intervals.

leetcodearrayintervalssimulation
LeetCode 468: Validate IP Address

A clear explanation of validating IPv4 and IPv6 addresses by checking segment count, length, characters, range, and leading-zero rules.

leetcodestringsimulation
LeetCode 446: Arithmetic Slices II - Subsequence

Count arithmetic subsequences of length at least three using dynamic programming with one hash map per ending index.

leetcodearraydynamic-programminghash-table
LeetCode 418: Sentence Screen Fitting

A clear explanation of fitting a sentence onto a screen using cyclic string simulation and greedy row transitions.

leetcodestringgreedysimulationdynamic-programming
LeetCode 395: Longest Substring with At Least K Repeating Characters

A clear explanation of finding the longest substring where every character appears at least k times using divide and conquer.

leetcodestringhash-tabledivide-and-conquersliding-window
LeetCode 370: Range Addition

A clear explanation of applying many range updates efficiently using a difference array and prefix sums.

leetcodearrayprefix-sumdifference-array
LeetCode 349: Intersection of Two Arrays

A clear explanation of Intersection of Two Arrays using hash sets for uniqueness and fast lookup.

leetcodearrayhash-tabletwo-pointerssorting
LeetCode 320: Generalized Abbreviation

A clear explanation of Generalized Abbreviation using backtracking to choose whether each character is kept or abbreviated.

leetcodestringbacktrackingbit-manipulation
LeetCode 300: Longest Increasing Subsequence

A dynamic programming and patience sorting solution for finding the longest strictly increasing subsequence in an array.

leetcodedynamic-programmingbinary-searcharray
LeetCode 494: Target Sum

A clear explanation of counting sign assignments that reach a target using recursion first, then subset-sum dynamic programming.

leetcodearraydynamic-programmingbacktrackingknapsack
LeetCode 417: Pacific Atlantic Water Flow

A clear explanation of finding cells that can flow to both oceans using reverse graph traversal from the borders.

leetcodematrixdfsbfsgraph
LeetCode 467: Unique Substrings in Wraparound String

A clear explanation of counting unique substrings that appear in the infinite alphabet wraparound string using dynamic programming by ending character.

leetcodestringdynamic-programming
LeetCode 319: Bulb Switcher

A clear explanation of Bulb Switcher using divisor parity and perfect squares.

leetcodemathbrainteaser
LeetCode 299: Bulls and Cows

A counting solution for producing the Bulls and Cows hint while handling duplicate digits correctly.

leetcodehash-tablestringcounting
LeetCode 445: Add Two Numbers II

Add two numbers stored in forward-order linked lists using stacks and carry propagation.

leetcodelinked-liststackmath
LeetCode 348: Design Tic-Tac-Toe

A clear explanation of Design Tic-Tac-Toe using row, column, and diagonal counters for constant-time winner checks.

leetcodedesignarrayhash-tablematrix
LeetCode 394: Decode String

A clear explanation of decoding nested repeat expressions using a stack.

leetcodestringstackrecursionparser
LeetCode 369: Plus One Linked List

A clear explanation of adding one to a number stored as a linked list using the rightmost non-nine digit.

leetcodelinked-listmath
LeetCode 493: Reverse Pairs

A clear explanation of counting pairs where nums[i] is greater than twice nums[j] using merge sort.

leetcodearraydivide-and-conquermerge-sortbinary-indexed-tree
LeetCode 318: Maximum Product of Word Lengths

A clear explanation of Maximum Product of Word Lengths using bit masks to test disjoint character sets efficiently.

leetcodearraystringbit-manipulation
LeetCode 416: Partition Equal Subset Sum

A clear explanation of deciding whether an array can be split into two equal-sum subsets using 0/1 knapsack dynamic programming.

leetcodearraydynamic-programmingknapsack
LeetCode 393: UTF-8 Validation

A clear explanation of validating a byte sequence as UTF-8 using bit masks and a continuation-byte counter.

leetcodearraybit-manipulationutf-8
LeetCode 444: Sequence Reconstruction

Check whether nums is the unique shortest supersequence of given subsequences using topological sorting.

leetcodegraphtopological-sortbfsqueue
LeetCode 466: Count The Repetitions

A clear explanation of counting how many repeated copies of one string can be obtained as a subsequence of another repeated string.

leetcodestringdynamic-programmingsimulation
LeetCode 368: Largest Divisible Subset

A clear explanation of finding the largest subset where every pair is divisible using sorting, dynamic programming, and parent reconstruction.

leetcodearraymathdynamic-programmingsorting
LeetCode 492: Construct the Rectangle

A clear explanation of finding rectangle dimensions with a fixed area and the smallest length-width difference.

leetcodemathfactorization
LeetCode 347: Top K Frequent Elements

A clear explanation of Top K Frequent Elements using frequency counting and bucket sort.

leetcodearrayhash-tablebucket-sortheap
LeetCode 298: Binary Tree Longest Consecutive Sequence

A DFS solution for finding the longest parent-to-child path where each node value increases by exactly one.

leetcodetreebinary-treedfs
LeetCode 297: Serialize and Deserialize Binary Tree

A preorder DFS codec for converting a binary tree to a string and reconstructing the same tree from that string.

leetcodetreebinary-treedfsdesignstring
LeetCode 225: Implement Stack using Queues

A clear explanation of implementing a LIFO stack using only FIFO queue operations.

leetcodestackqueuedesign
LeetCode 443: String Compression

Compress a character array in-place using two pointers and grouped character counting.

leetcodearraystringtwo-pointers