brain

tamnd's digital brain — notes, problems, research

43815 notes

LeetCode 504: Base 7

A clear explanation of converting an integer into its base 7 string representation using repeated division.

leetcodemathstringnumber-system
LeetCode 503: Next Greater Element II

A clear explanation of finding the next greater element in a circular array using a monotonic stack.

leetcodearraystackmonotonic-stackcircular-array
LeetCode 927: Three Equal Parts

A clear explanation of solving Three Equal Parts by counting ones, locating the three binary patterns, and comparing them in one pass.

leetcodearraybinarygreedy
LeetCode 977: Squares of a Sorted Array

A clear explanation of sorting squared values from a sorted array using two pointers.

leetcodearraytwo-pointerssorting
LeetCode 952: Largest Component Size by Common Factor

A clear explanation of solving Largest Component Size by Common Factor using prime factorization and union find.

leetcodearraymathnumber-theoryunion-find
LeetCode 877: Stone Game

A clear explanation of the Stone Game problem using game theory and interval dynamic programming.

leetcodearraydynamic-programminggame-theoryinterval-dp
LeetCode 902: Numbers At Most N Given Digit Set

A clear explanation of counting numbers less than or equal to N using digit-by-digit construction and combinatorics.

leetcodemathdigit-dpcombinatorics
LeetCode 852: Peak Index in a Mountain Array

A clear explanation of finding the peak index in a mountain array using binary search.

leetcodearraybinary-search
LeetCode 827: Making A Large Island

A clear explanation of the Making A Large Island problem using connected component labeling and island size lookup.

leetcodearraymatrixdepth-first-searchbreadth-first-searchunion-find
LeetCode 802: Find Eventual Safe States

A graph traversal solution for finding all nodes that cannot reach a directed cycle.

leetcodegraphdfscycle-detection
LeetCode 777: Swap Adjacent in LR String

A clear explanation of validating string transformation using two pointers and movement constraints.

leetcodestringtwo-pointers
LeetCode 752: Open the Lock

A clear explanation of solving Open the Lock using breadth-first search over lock states.

leetcodebfsgraphhash-setstring
LeetCode 727: Minimum Window Subsequence

Find the shortest substring of s1 that contains s2 as a subsequence using dynamic programming.

leetcodestringdynamic-programmingsubsequence
LeetCode 976: Largest Perimeter Triangle

A clear explanation of finding the largest valid triangle perimeter using sorting and a greedy scan.

leetcodearraysortinggreedytriangle-inequality
LeetCode 951: Flip Equivalent Binary Trees

A clear explanation of checking whether two binary trees are equivalent after swapping left and right children at any number of nodes.

leetcodetreebinary-treedfsrecursion
LeetCode 926: Flip String to Monotone Increasing

A clear explanation of solving Flip String to Monotone Increasing with a one-pass dynamic programming approach.

leetcodedynamic-programmingstringgreedy
LeetCode 901: Online Stock Span

A clear explanation of Online Stock Span using a monotonic decreasing stack with accumulated spans.

leetcodestackmonotonic-stackdesigndata-stream
LeetCode 876: Middle of the Linked List

A clear explanation of finding the middle node of a singly linked list using slow and fast pointers.

leetcodelinked-listtwo-pointersslow-fast-pointer
LeetCode 851: Loud and Rich

A clear explanation of Loud and Rich using graph traversal, DFS, and memoization.

leetcodegraphdfsmemoizationtopological-sort
LeetCode 826: Most Profit Assigning Work

A clear explanation of the Most Profit Assigning Work problem using sorting, greedy choice, and two pointers.

leetcodearraysortinggreedytwo-pointers
LeetCode 801: Minimum Swaps To Make Sequences Increasing

A dynamic programming solution for finding the minimum number of same-index swaps needed to make two arrays strictly increasing.

leetcodedynamic-programmingarray
LeetCode 776: Split BST

A clear explanation of splitting a binary search tree into two BSTs using recursion and pointer rewiring.

leetcodetreebinary-search-treerecursion
LeetCode 751: IP to CIDR

A clear explanation of converting a range of IPv4 addresses into the shortest list of CIDR blocks using greedy bit manipulation.

leetcodebit-manipulationstringgreedycidr
LeetCode 726: Number of Atoms

Parse a chemical formula with nested parentheses, atom names, and multipliers using recursive descent.

leetcodestringstackhash-mapsortingparsing
LeetCode 701: Insert into a Binary Search Tree

A clear explanation of inserting a value into a binary search tree using recursive and iterative traversal.

leetcodebinary-treebinary-search-treerecursiontree
LeetCode 676: Implement Magic Dictionary

Design a dictionary that can check whether a word can match a stored word after changing exactly one character.

leetcodehash-mapstringdesign
LeetCode 652: Find Duplicate Subtrees

A clear explanation of finding duplicate binary tree subtrees using postorder traversal, serialization, and a hash map.

leetcodetreebinary-treehash-mapdepth-first-searchserialization
LeetCode 602: Friend Requests II: Who Has the Most Friends

A SQL guide for counting friendships from both requester and accepter sides, then returning the user with the most friends.

leetcodesqlunion-allgroup-bydatabase
LeetCode 502: IPO

A clear explanation of maximizing capital by selecting at most k projects using sorting and a max heap.

leetcodegreedyheappriority-queuesorting
LeetCode 537: Complex Number Multiplication

A clear explanation of multiplying complex numbers represented as strings using algebraic expansion.

leetcodemathstringsimulation
LeetCode 586: Customer Placing the Largest Number of Orders

A clear SQL guide for finding the customer who placed the most orders.

leetcodesqlgroup-byorder-byaggregation
LeetCode 561: Array Partition

A clear explanation of Array Partition using sorting and adjacent pairing to maximize the sum of pair minimums.

leetcodearraygreedysorting
LeetCode 651: 4 Keys Keyboard

A dynamic programming solution for maximizing the number of A characters printed with a limited number of keyboard operations.

leetcodedynamic-programmingmath
LeetCode 626: Exchange Seats

A SQL solution for swapping every pair of adjacent student seats while leaving the final seat unchanged when the row count is odd.

leetcodesqlcasesorting
LeetCode 601: Human Traffic of Stadium

A SQL guide for finding stadium records that belong to runs of at least three consecutive ids where each row has at least 100 people.

leetcodesqlwindow-functiongroupingdatabase
LeetCode 501: Find Mode in Binary Search Tree

A clear explanation of finding the most frequent value or values in a binary search tree using inorder traversal.

leetcodebinary-treebinary-search-treedfsinorder-traversal
LeetCode 536: Construct Binary Tree from String

A clear explanation of parsing a parenthesized string recursively to construct a binary tree.

leetcodetreebinary-treerecursionstringparsing
LeetCode 585: Investments in 2016

A clear SQL guide for summing 2016 investments for policies with repeated 2015 investment values and unique locations.

leetcodesqlgroup-byhavingaggregation
LeetCode 560: Subarray Sum Equals K

A clear explanation of Subarray Sum Equals K using prefix sums and a hash map to count matching subarrays in linear time.

leetcodearrayhash-mapprefix-sum
LeetCode 535: Encode and Decode TinyURL

A clear explanation of designing a simple URL encoder and decoder using a hash map and generated keys.

leetcodedesignhash-tablestring
LeetCode 534: Game Play Analysis III

A clear explanation of computing cumulative games played per player and date using SQL window functions.

leetcodesqldatabasewindow-functionaggregation
LeetCode 584: Find Customer Referee

A clear SQL guide for selecting customers who were not referred by customer 2, including customers with no referee.

leetcodesqlwherenull
LeetCode 559: Maximum Depth of N-ary Tree

A clear explanation of Maximum Depth of N-ary Tree using recursive depth-first search.

leetcodetreedepth-first-searchbreadth-first-search
LeetCode 583: Delete Operation for Two Strings

A clear dynamic programming solution for finding the minimum deletions needed to make two strings equal.

leetcodedynamic-programmingstringlcs
LeetCode 558: Logical OR of Two Binary Grids Represented as Quad-Trees

A clear explanation of merging two quad-trees using recursive logical OR operations.

leetcodetreequad-treerecursion
LeetCode 533: Lonely Pixel II

A clear explanation of counting black lonely pixels using row counts, column counts, and duplicate row patterns.

leetcodearraymatrixhash-tablecounting
LeetCode 557: Reverse Words in a String III

A clear explanation of Reverse Words in a String III using two-pointer scanning and string reversal.

leetcodestringtwo-pointers
LeetCode 532: K-diff Pairs in an Array

A clear explanation of counting unique pairs whose absolute difference is k using frequency counting.

leetcodearrayhash-tablecounting
LeetCode 582: Kill Process

A clear graph traversal solution for finding all processes terminated when killing a target process.

leetcodetreegraphdfsbfshash-map
LeetCode 581: Shortest Unsorted Continuous Subarray

A clear linear-time solution for finding the shortest subarray that must be sorted to make the whole array sorted.

leetcodearraytwo-pointersscanning
LeetCode 556: Next Greater Element III

A clear explanation of Next Greater Element III using the next permutation algorithm on the digits of an integer.

leetcodemathstringtwo-pointerspermutation
LeetCode 531: Lonely Pixel I

A clear explanation of counting black pixels that are alone in both their row and column.

leetcodearraymatrixcounting
LeetCode 555: Split Concatenated Strings

A clear explanation of Split Concatenated Strings using string reversal choices and enumeration of every possible cut point.

leetcodestringgreedyenumeration
LeetCode 580: Count Student Number in Departments

A clear SQL guide for counting students in every department, including departments with zero students.

leetcodesqlleft-joingroup-byaggregation
LeetCode 530: Minimum Absolute Difference in BST

A clear explanation of finding the minimum difference between two BST node values using inorder traversal.

leetcodetreebinary-search-treedepth-first-searchinorder-traversal
LeetCode 579: Find Cumulative Salary of an Employee

A clear SQL guide for computing each employee's 3-month cumulative salary while excluding their most recent month.

leetcodesqlwindow-functionself-joinaggregation
LeetCode 554: Brick Wall

A clear explanation of Brick Wall using prefix sums and a hash map to find the best vertical cut position.

leetcodearrayhash-mapprefix-sum
LeetCode 529: Minesweeper

A clear explanation of updating a Minesweeper board using DFS flood fill and adjacent mine counting.

leetcodearraymatrixdepth-first-searchbreadth-first-search
LeetCode 553: Optimal Division

A clear explanation of Optimal Division using the structure of division expressions to build the maximum-value expression.

leetcodearraymathstring
LeetCode 578: Get Highest Answer Rate Question

A clear SQL guide for finding the question with the highest answer rate from survey logs.

leetcodesqlgroup-byaggregationorder-by
LeetCode 528: Random Pick with Weight

A clear explanation of weighted random sampling using prefix sums and binary search.

leetcodearrayprefix-sumbinary-searchrandomized
LeetCode 552: Student Attendance Record II

A clear explanation of Student Attendance Record II using dynamic programming over absence count and late streak.

leetcodedynamic-programmingstringcounting
LeetCode 577: Employee Bonus

A clear SQL guide for finding employees whose bonus is less than 1000 or missing.

leetcodesqlleft-joinnull
LeetCode 527: Word Abbreviation

A clear explanation of generating minimal unique word abbreviations using grouping and trie prefixes.

leetcodestringtriegreedysorting
LeetCode 576: Out of Boundary Paths

A clear dynamic programming solution for counting paths that move a ball out of a grid boundary.

leetcodedynamic-programmingmemoizationgrid
LeetCode 551: Student Attendance Record I

A clear explanation of Student Attendance Record I using simple string checks and a one-pass counter solution.

leetcodestringsimulation
LeetCode 526: Beautiful Arrangement

A clear explanation of counting beautiful arrangements using backtracking and divisibility pruning.

leetcodebacktrackingdynamic-programmingbitmask
Chapter 5. Arithmetic Geometry and Modern Directions

Arithmetic geometry studies solutions of polynomial equations by combining algebra, geometry, and number theory. Its basic objects are spaces defined by polynomial equations....

number-theorybook
Chapter 4. Algebraic Number Theory

A field is a number system in which addition, subtraction, multiplication, and division by nonzero elements are always possible. The rational numbers $\mathbb{Q}$, the real...

number-theorybook
Chapter 3. Analytic Number Theory

The harmonic series is the infinite series

number-theorybook
Chapter 2. Classical Number Theory

A Diophantine equation is an equation whose solutions are required to be integers. The unknowns are not allowed to range over the real numbers or complex numbers unless...

number-theorybook
Divisibility Relations

Division of integers does not always produce an integer. For example,

number-theorybook
Historical Development of Number Systems

The idea of number arose long before formal mathematics. Early civilizations used numbers for counting objects, measuring land, recording trade, and tracking time.

number-theorybook
Growth of Integers

The integers extend infinitely in both directions:

number-theorybook
Recursive Definitions

Many mathematical objects are defined recursively. A recursive definition specifies:

number-theorybook
Strong Induction

Ordinary induction proves a statement $Pn$ by showing that truth passes from one case to the next:

number-theorybook
Mathematical Induction

Many statements in number theory concern all natural numbers. For example, one may wish to prove that

number-theorybook
Absolute Value and Distance

The order relation distinguishes positive and negative integers, but in many situations the sign of a number is less important than its magnitude. For example, the integers

number-theorybook
Order Relations

The integers are not merely a collection of numbers equipped with arithmetic operations. They also possess an order structure. Given two integers $a$ and $b$, one can...

number-theorybook
Arithmetic Operations

An arithmetic operation is a rule that combines numbers to produce another number. The most basic operations on integers are addition, subtraction, multiplication, and division.

number-theorybook
The Integers

The natural numbers are sufficient for counting and addition, but they are not sufficient for subtraction. For example,

number-theorybook
Chapter 1. Foundations of Arithmetic

The natural numbers arise from the basic act of counting. When we count objects in a collection, we assign successive numbers:

number-theorybook
Chapter 22. Open Problems

Automatic differentiation works naturally on pure mathematical functions:

autodiffbook
Differentiation of Large Stateful Systems

Automatic differentiation works naturally on pure mathematical functions:

autodiffbook
Differentiation of Large Stateful Systems

Automatic differentiation works naturally on pure mathematical functions:

autodiffbook
Production Deployment

A minimal automatic differentiation engine can compute correct gradients on small programs. A production system must survive long-running workloads, large tensors, distributed...

autodiffbook
Unified Differentiable Infrastructure

Automatic differentiation began as a numerical technique for computing gradients of scalar functions.

autodiffbook
Chapter 16. Sparse and Structured Differentiation

Sparse and structured differentiation studies how to compute derivatives without materializing dense derivative objects. Many real systems have enormous Jacobians and...

autodiffbook
Physics-Informed Models

Physics-informed models combine data fitting with equations from physics or applied mathematics. The model is trained not only to match observed samples, but also to satisfy...

autodiffbook
Effect Systems and Mutation

Automatic differentiation is easiest to define for pure functions. A pure function behaves like a mathematical mapping: it consumes inputs, produces outputs, and has no...

autodiffbook
Ahead-of-Time vs Just-in-Time Differentiation

Automatic differentiation can be performed before a program runs, while it runs, or in a staged phase between the two.

autodiffbook
Case Studies

This section studies reverse mode automatic differentiation through concrete examples. Each case has the same structure:

autodiffbook
Tangent Propagation

Forward mode automatic differentiation computes derivatives by propagating tangent values alongside ordinary values. The ordinary value is called the primal. The derivative...

autodiffbook
Taylor Expansions

Differentiation describes how a function changes locally. A Taylor expansion extends this idea by approximating a function with a polynomial around a point.

autodiffbook
Comparative Architecture Analysis

The systems in this chapter show that automatic differentiation is not one implementation technique. It is a family of program transformations. Each system chooses a different...

autodiffbook
Comparative Architecture Analysis

The systems in this chapter show that automatic differentiation is not one implementation technique. It is a family of program transformations. Each system chooses a different...

autodiffbook
Testing Derivatives

An automatic differentiation engine is only useful if its derivatives are correct. A small mistake in a backward rule can silently corrupt optimization, training, or...

autodiffbook
Differentiation as Functorial Transformation

The preceding sections described automatic differentiation through algebraic, categorical, logical, and denotational models. These viewpoints converge on one central idea:

autodiffbook
Verified Differentiation

Automatic differentiation systems are usually trusted because they implement mathematically established rules such as the chain rule, product rule, and linearization of...

autodiffbook
Distributed Gradient Computation

Distributed gradient computation appears when a differentiable program no longer fits comfortably on one device or one machine. The reason may be model size, data volume,...

autodiffbook