Mathematics
math
Foundations
Basic Proof Techniques
Goldbach's conjecture has been verified for every even integer up to 4 * 10^18, yet mathematicians still call it a conjecture because no amount of testing covers every case. Algorithm correctness has the same shape: a function can pass a hundred unit tests and still fail on the empty list or the input size your tests never reached. **Basic Proof Techniques** equips you with the small set of argument styles that turn intuition into certainty about correctness, complexity bounds, and data structure invariants. Direct proof chains definitions and prior facts to a claim. Proof by contradiction assumes the opposite and derives a logical impossibility, as in the irrationality of `sqrt(2)` and the `Omega(n log n)` lower bound for comparison sorts. Mathematical induction, in weak and strong forms, proves statements over the natural numbers via a base case and an inductive step, the backbone of recurrence solutions and loop invariants. Proof by contraposition swaps `P implies Q` for the equivalent `not Q implies not P`, and proof by cases breaks a claim into exhaustive subcases. This lesson builds on **Discrete Mathematics Basics**, where you met sets, propositional logic, implications, and the first taste of formal proof. Here those informal sketches become the disciplined patterns that algorithm analysis, theoretical CS, and clean engineering arguments all rely on. With proofs in hand, you have completed the foundations track and are ready to step into **Arrays & Strings** and the rest of the data structures curriculum, armed to analyze every operation rigorously.
Not Started
0%
Combinatorics Basics
How many ways can you arrange `n` items? How many subsets does a set of size `n` have? Questions like these are not idle puzzles, they are exactly the questions you have to answer to know whether a brute-force solution will run in milliseconds or in millennia. **Combinatorics Basics** gives you the counting tools that turn vague statements like "try every possibility" into precise complexity claims. This lesson covers the four counting ideas you will rely on throughout DSA. The **rule of sum** and **rule of product** let you decompose multi-step processes and count outcomes; **permutations** count ordered arrangements (`n!` for arranging all of them, `nPr` for choosing `r` in order); **combinations** count unordered selections (`nCr`, also written as binomial coefficients); and **Pascal's triangle** plus a first look at **basic probability** tie everything together. You will see why a set of size `n` has `2^n` subsets, why generating all permutations of an array is `O(n!)`, and how counting principles directly produce the time complexity of backtracking algorithms. This lesson builds on **Discrete Mathematics Basics**, where you formalized sets, set operations, and logic. Combinatorics is what happens when you start asking "how many?" about those sets, ordered or unordered, with or without repetition. With the counting toolkit in place you will continue the math track in **Number Theory Fundamentals**, picking up primes, divisibility, and `gcd`, the other half of the math you need for hashing, cryptography-style problems, and modular arithmetic.
Not Started
0%
Discrete Mathematics Basics
Almost every conditional you have ever written is a tiny piece of propositional logic, and almost every collection you have ever stored is, mathematically, a set. **Discrete Mathematics Basics** makes that connection explicit, giving you the formal vocabulary that data structures, graph algorithms, database queries, and correctness arguments all sit on top of. This lesson walks you through three pillars of discrete math used throughout DSA. First, **sets** and the operations on them: union, intersection, difference, complement, subset, and membership, the same ideas baked into hash sets and array problems. Second, **propositional logic**: the operators `AND`, `OR`, `NOT`, and implication, plus truth tables for evaluating compound expressions; this is the math behind every Boolean condition in your code. Third, **binary relations** and their properties (reflexive, symmetric, transitive), which generalize the way edges connect nodes in graphs and rows connect in databases. Along the way you will get a first taste of formal proof: how to argue that two sets are equal or that a logical equivalence always holds. This lesson assumes only basic programming familiarity, so no specific DSA prerequisite is required. If you have written `if (x && !y)` or used a hash set, you already have informal intuition for everything we will formalize here. From here you will move into **Combinatorics Basics**, where you will use these set and counting foundations to count permutations, combinations, and arrangements (the math behind backtracking and many complexity proofs).
Not Started
0%
Logarithms & Exponentiation
How can a search through a million sorted items finish in roughly twenty comparisons? The answer is `log_2(n)`, and once you internalize what that expression really means, an entire family of fast algorithms (binary search, balanced trees, divide-and-conquer) suddenly stops feeling like magic. **Logarithms & Exponentiation** builds your intuition for the math behind `O(log n)`. You will start from a concrete framing (a logarithm answers the question "how many times can I halve `n` before reaching 1?") and work through the powers-of-2 sequence (1, 2, 4, 8, 16, ...) that appears constantly in computer science. You will pick up the three logarithm properties you actually need (`log(a * b) = log(a) + log(b)`, `log(a^n) = n * log(a)`, and `log(1) = 0`), see why the base does not matter inside Big-O, meet fast exponentiation as a preview of `O(log n)` in action, and trace why every halving loop produces logarithmic complexity. In **Big-O Notation (Upper Bound)**, you learned that `O(log n)` sits between `O(1)` and `O(n)` in the hierarchy and is associated with algorithms that halve their work each step. This lesson supplies the mathematical reason that pattern produces a logarithm, so the complexity class stops being something you memorize and starts being something you can derive. Once logarithms feel comfortable, you will be ready for **Mathematical Sequences**, where you will study arithmetic sums, geometric series, and Fibonacci patterns that explain the running times of everything from nested loops to recursive algorithms.
Not Started
0%
Mathematical Sequences
Why is a triangular nested loop that does `1 + 2 + 3 + ... + n` units of work classified as `O(n^2)` rather than `O(n)`? Because the closed form of that sum is `n(n+1)/2`, which grows quadratically. The same kind of summation argument explains why merge sort is `O(n log n)`, why a doubling array gives amortized `O(1)` insertions, and why naive recursive Fibonacci is exponentially slow. **Mathematical Sequences** equips you with the essential sequences and summation formulas behind algorithm analysis. You will work with arithmetic sequences (where each term adds a constant) and the formula `1 + 2 + ... + n = n(n+1)/2`, geometric sequences (where each term multiplies by a constant ratio) and their geometric-series sum, and the Fibonacci sequence defined by `F(n) = F(n-1) + F(n-2)`. You will then connect these formulas back to code: triangular nested loops, halving-and-doubling patterns, and the canonical recursive Fibonacci that motivates dynamic programming. In **Big-O Notation (Upper Bound)**, you learned to spot dominant terms and to drop constants and lower-order terms. This lesson supplies the closed-form summations that turn a step count like `1 + 2 + ... + n` into a precise polynomial you can simplify with confidence. With these summation tools in hand, you will be ready for **Debugging by Tracing**, where you will sharpen the step-by-step execution skills you need to verify that the algorithms you analyze actually behave the way your formulas predict.
Not Started
0%
Modular Arithmetic
Open any production hash table, any block cipher, any RSA implementation, or any competitive programming problem that ends in "output the answer modulo `10^9 + 7`", and you will find the same machinery underneath: **modular arithmetic**, the math of working with remainders rather than full integers. It is the bridge between number theory and a huge swath of real algorithms. This lesson develops that machinery from first principles. You will revisit the `mod` operation precisely (including its relationship to division and remainders), then prove and use the addition, subtraction, and multiplication rules that let you take `mod` at every step of a long calculation without changing the answer. From there you will implement **fast modular exponentiation** in `O(log n)` time using binary exponentiation, compute **modular inverses** with **Fermat's Little Theorem** when the modulus is prime, and see exactly why hash tables, RSA, and contest problems rely on these tricks to avoid overflow and to invert multiplications. This lesson builds on **Number Theory Fundamentals**, where you learned about primes, divisibility, `gcd`, and the Euclidean algorithm. Modular arithmetic uses all of those: primality lets you apply Fermat, `gcd` decides when an inverse exists, and divisibility underlies every congruence. From here the only foundations topic remaining is **Basic Proof Techniques**, where you will learn the proof tools (induction, contradiction, contraposition) that make the kinds of arguments you have just been waving at fully rigorous.
Not Started
0%
Number Theory Fundamentals
Why are hash table sizes almost always prime? Why does the Euclidean algorithm for `gcd` run in `O(log(min(a, b)))` time despite using only subtraction or remainders? **Number Theory Fundamentals** is the branch of math that answers these questions and quietly powers a surprising amount of practical software, from hashing and cryptography to scheduling and competitive programming shortcuts. This lesson introduces the core building blocks. You will study **prime numbers** and how to test primality efficiently, the **divisibility** relation and quick rules for spotting divisors, **GCD** (greatest common divisor) and **LCM** (least common multiple) with the identity `lcm(a, b) = a * b / gcd(a, b)`, and the **Euclidean algorithm** for computing `gcd` in logarithmic time. You will also do **prime factorization** by trial division (`O(sqrt(n))`) and see how factorizations make divisor counting, simplification, and periodicity arguments straightforward. This lesson builds on **Discrete Mathematics Basics**, where you learned how to reason precisely about sets, relations, and logical claims. Number theory uses that same proof-style reasoning, but applied to the integers and their multiplicative structure. With primes, `gcd`, and factorization in your toolkit, you will be ready to take the premium step into **Modular Arithmetic**, where you will reuse all of these ideas to work with `mod`, modular inverses, and Fermat's Little Theorem.
Not Started
0%
Algorithms
Mathematical Algorithms
Computing `a^b mod m` for `a = 7`, `b = 10^18`, and `m = 10^9 + 7` looks impossible: even iterating one multiplication per step would take longer than the age of the universe. Binary exponentiation does it in 60 multiplications, by squaring the base while halving the exponent. RSA encryption depends on exactly this trick, and so do most modular-arithmetic problems in competitive programming. **Mathematical Algorithms** assembles the standard toolkit. You will implement the Sieve of Eratosthenes for primes up to `N` in `O(N log log N)`, plus the segmented sieve for large ranges. Binary exponentiation handles `a^b mod m` in `O(log b)`, and the matrix-exponentiation generalization computes Fibonacci or any linear recurrence in `O(log n)`. You will derive the Extended Euclidean algorithm for `ax + by = gcd(a, b)` and use it for modular inverses, walk through the Chinese Remainder Theorem, compute Euler's totient, apply Fermat's Little Theorem to modular inversion, and run the Miller-Rabin probabilistic primality test. In **Number Theory Fundamentals**, you saw GCD, primes, and divisibility. **Modular Arithmetic** introduced congruences and modular inverses. This lesson turns those facts into algorithms that scale to numbers the problem statement actually asks about. Next, **Computational Geometry** turns to algorithmic problems on points, lines, and polygons.
Not Started
0%
Practice Problems
Add Binary
Given two binary strings, return their sum as a binary string.
Happy Number
Determine if a number is happy by repeatedly replacing it with the sum of the squares of its digits until it reaches 1 or enters a cycle.
Missing Number
Given an array of n distinct numbers from the range [0, n], find the one number that is missing from the array.
Palindrome Number
Determine whether an integer is a palindrome without converting it to a string, by reversing half of the number and comparing.
Plus One
Given a large integer represented as an array of digits, increment it by one and return the resulting array of digits.
Max Points on a Line
Given an array of points on a 2D plane, find the maximum number of points that lie on the same straight line.
Detect Squares
Design a data structure that supports adding points on a 2D plane and counting the number of ways to form axis-aligned squares with a given query point as one corner.
Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n! (n factorial). Trailing zeroes are produced by factors of 10, and since 10 = 2 * 5, count the number of times 5 appears as a factor.
Multiply Strings
Given two non-negative integers represented as strings, return their product as a string. You must not convert the inputs to integers directly or use any built-in BigInteger library.
Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n). Use binary exponentiation (fast power) to achieve O(log n) time complexity.
Reverse Integer
Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows the 32-bit signed integer range, return 0.
Sqrt(x)
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. Use binary search to achieve O(log x) time without using built-in exponent functions.
String to Integer (atoi)
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. Handle leading whitespace, optional sign, digit parsing, and integer overflow/underflow.
Sum of Two Integers
Calculate the sum of two integers a and b without using the operators + or -. Use bitwise operations to simulate addition.
Code Snippets
Clamp a Number Within a Range
Clamping a value into `[min, max]` shows up in scroll math, slider components, RGB arithmetic, and clamping pagination cursors. The one-liner is trivial, but the helpful version handles swapped bounds, `NaN`, and integer-only callers. This snippet covers the simple form, an `inclusive`/`exclusive` mapping flag, and an integer variant that snaps to whole numbers in the range.
Format Bytes as a Human String
Showing `1457280 bytes` is hostile UX; showing `1.39 MB` (or `1.46 MB` if you use SI) is what users expect. This snippet covers the binary IEC variant (KiB, MiB, GiB), the decimal SI variant (KB, MB, GB), and a configurable helper that picks the unit, precision, and separator. Use it for upload progress, storage dashboards, or anywhere a raw byte count would otherwise leak into the UI.
Random Integer in a Range
Off-by-one bugs in random integer helpers are the silent kind: tests pass, distributions look right, but the maximum value never appears. This snippet covers the inclusive `[min, max]` form most people actually want, the unbiased version using `crypto.getRandomValues`, and a helper for picking a uniform random element from an array. Use it for sampling, dice rolls, jitter, and quick demos.
Numeric Aggregations: Sum, Filter, Closest Pair
Three numeric questions you will hit again and again on real arrays: sum (with safety against non-number inputs), summary statistics (sum, average, min, max in one pass), and the smallest absolute difference between any two numbers. Each one is short, but the right answer changes with the input shape: mixed-type arrays, large arrays, and "closest pair" all reward different idioms.
Number Tricks: Integer Check, Digit Length, Exponent, GCD, Primes, Random Hex
A collection of small number-theory and number-formatting recipes that show up constantly: inspecting a number (integer check, digit length), looped algorithms (binary exponent, Euclidean GCD, prime listing), digit-level transforms (sort, reverse, sum), and a couple of random helpers (hex color, plus pointers to the existing range and shuffle entries). Each accordion is its own tight group so you can pull just the recipe you need.
Question Banks
Number Theory Warm-Up
Short drills on GCD, LCM, modular arithmetic, and modular exponentiation. A gentle on-ramp for interview problems that lean on integer math identities.
Floating Point and Precision
Hard drills on IEEE-754 representation, equality pitfalls, accumulation drift, and safe comparison patterns. Includes one Kahan-summation walk and a 0.1 + 0.2 trace.
Numeric Puzzles and FizzBuzz Challenges
Six numeric warm-ups: recursive exponent, random sampling, prime check, recursive 1..n, completing missing numbers, and iterative Fibonacci.
JavaScript FizzBuzz: Two Implementations Quiz
Two seeded FizzBuzz implementations (modulo branching and order-sensitive variant) plus two companion drills covering a generalized N-divisors version and a micro-benchmark.
JavaScript Min/Max Leave-One-Out Sum: Three Approaches Quiz
Compute the smallest and largest "drop one and sum the rest" totals three ways (sort + slice, total-sum minus extremum, single-pass min/max tracker), plus two companions on streaming inputs and a top-K leave-out generalisation.
JavaScript Missing Numbers Finder: Two Approaches Quiz
Find missing integers between the min and max of an array, two ways (sort + gap-walk and Set diff over min..max), plus companions on the consecutive-1..n case and detecting duplicates.
JavaScript Largest Difference in Array: Three Approaches Quiz
Three seeded ways to compute the maximum pairwise gap in an integer array (sort and subtract ends, reduce with Math.max and Math.min, single-pass tracker), plus two companions on edge cases and complexity.
JavaScript Recipe Batches: Two Approaches Quiz
Two seeded ways to compute how many full batches can be produced from available materials (imperative loop with Math.min and a reduce-based variant), plus two companions on missing-key handling and zero-quantity edge cases.
JavaScript Factorial: Three Implementations Quiz
Three seeded ways to compute n! (iterative loop, classic recursion, reduce), plus two companions on memoization and on guarding against negative inputs.
JavaScript Square and Join Digits: Two Approaches Quiz
Two seeded ways to square each digit of an integer and concatenate the results (string split with map and join, plus a while-loop modulo extraction), with two companions on negative numbers and on returning a string.
Community
Hamming Distance
Count the bit positions where two non-negative integers differ using XOR plus a population-count loop.
Excel Sheet Column Number
Convert a spreadsheet column title (`A`, `Z`, `AA`, `AB`, ...) into its 1-based column number using bijective base-26.
ML Engineer Onsite: The Whiteboard Math Round
An ML onsite at a Series D recommendation-systems company, anchored on the math round where I had to derive a logistic regression gradient on a whiteboard.
Arranging Coins
Find the largest k such that 1+2+...+k <= n, framed as a binary-search-on-answer warmup with a closed-form sanity check.
Power of Two
Determine whether a 32-bit signed integer is a power of two using a single bit-AND trick.
Power of Three
Decide whether a 32-bit signed integer is a power of three using a divisibility shortcut against the largest 32-bit power of three.
Modular Arithmetic for the Working Programmer
Modulo without the math-class baggage: the four laws that matter, the negative-number trap that ruins hash and rotation code, modular inverses, and where I actually use this in production.
Expression Add Operators
Insert +, -, * between digits of a string so the resulting expression equals a target, using backtracking that handles operator precedence in O(1) per step.
Bit Manipulation Tricks I Keep Forgetting
A working programmer's cheat sheet of bitwise operations: the moves I look up every six months, what each one does, real production uses, and the ones that look clever but I avoid.
Beautiful Arrangement
Count the permutations of 1..n where every i either divides perm[i] or is divided by perm[i], using backtracking with divisibility pruning.
