Math & Geometry
Number theory, overflow-safe arithmetic, fast powers, primes, cross products and random sampling: the small set of math tools that turns brute force into O(log n) or O(1).
Overview
Math problems in coding rarely need advanced math. They need a handful of tools you can write from memory: Euclid's algorithm, fast exponentiation, the sieve, modular arithmetic, the cross product and two sampling algorithms. The skill being tested is spotting which tool fits, then writing it without overflow or off-by-one bugs.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
Spot the tool
The rule: read the problem for the signal, then reach for the tool. Most brute-force answers are O(n) or worse; the tool usually gives O(log n) or O(1).
Two more signals have simple tools of their own.
- Digits of a number, reversing it, a palindrome: % 10 and // 10 in a loop, in O(number of digits).
- Boxes or intervals that overlap: the max of the starts and the min of the ends, in O(1).
> [!NOTE] > Matrix rotation and spiral order look like geometry but are index bookkeeping; they live in the Matrix topic.
The rest of this chapter takes the tools one at a time, starting with the oldest.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio