Pattern 17 of 20
Math & Geometry
Number properties, modular arithmetic and coordinates: careful reasoning over brute force.
When to use it
- Digits, primes, powers, greatest common divisors
- Rotating, spiralling or reflecting a matrix of points
- Results that overflow without care
The idea
Look for the mathematical rule that removes the loop: a formula, a cycle in the values or a symmetry. Then handle the edges carefully: negative numbers, zero and overflow.
Typical cost Often O(log n) or O(1); matrix transforms are O(n·m).
How it works
Math problems reward spotting a structure that makes simulation unnecessary. Instead of repeating an operation a billion times, find the invariant, the cycle, or the closed formula. Exponentiation by squaring, modular arithmetic and digit manipulation are the everyday tools.
Fast power works because x^n splits into (x^(n/2))², so the number of multiplications follows the bits of n: about log n of them. The same doubling trick applies to matrix powers and to repeated application of any associative operation.
Geometry in interviews usually means grids and coordinates: rotating a matrix, counting points on a line, detecting squares. Prefer integer arithmetic. To compare slopes, store the reduced pair (dy, dx) divided by their greatest common divisor rather than a floating-point ratio.
Watch for overflow and sign. Reversing digits, multiplying large strings, or computing averages can exceed 32-bit limits, and the remainder of a negative number differs between languages. Many problems state 'return the answer modulo 10^9 + 7' precisely so you reduce after every operation.
How to attack it
- 1Look for a formula, invariant or cycle before simulating.
- 2Use integer arithmetic; avoid floats for equality checks.
- 3Reduce modulo M after every addition and multiplication if the answer is modular.
- 4Check negative inputs, zero, and the largest allowed values for overflow.
- 5For digit problems, peel digits with % 10 and // 10 instead of converting to strings when overflow matters.
Template
A skeleton to adapt, not a solution to paste. Write it from memory a few times.
def fast_pow(base, exp, mod=None):
# Exponentiation by squaring: O(log exp) multiplications.
result = 1
while exp > 0:
if exp & 1: # this bit of exp is set
result = result * base if mod is None else result * base % mod
base = base * base if mod is None else base * base % mod
exp >>= 1
return result
def gcd(a, b):
while b:
a, b = b, a % b
return abs(a)
def slope_key(p, q):
# A hashable, exact slope between two points: reduced (dy, dx) with dx >= 0.
dy, dx = q[1] - p[1], q[0] - p[0]
g = gcd(dy, dx) or 1
dy, dx = dy // g, dx // g
if dx < 0 or (dx == 0 and dy < 0):
dy, dx = -dy, -dx
return (dy, dx)
def digit_sum(n):
total = 0
n = abs(n)
while n:
total += n % 10
n //= 10
return totalVariants
- Fast exponentiation
- Square the base and halve the exponent; handles negative exponents by inverting the result at the end.
- Digit manipulation
- Reverse, sum or test digits with % 10 and integer division, checking overflow before each step.
- Cycle detection on numbers
- Repeatedly apply a function (such as sum of squared digits) and detect a loop with a set or with fast and slow pointers.
- Points and slopes
- Group points by a reduced (dy, dx) slope key to find collinear points without floating-point error.
- Big-number arithmetic
- Multiply or add numbers stored as strings digit by digit, like long multiplication on paper.
Pitfalls
- Comparing floating-point slopes or distances for equality.
- Integer overflow when reversing digits or multiplying; JavaScript loses precision past 2^53.
- Negative remainders: -7 % 3 is 2 in Python but -1 in JavaScript.
- Forgetting the zero exponent, a zero base, or a negative exponent in power functions.
- Simulating a huge number of steps when a cycle or formula exists.
What it costs
| Operation | Cost |
|---|---|
| Fast power | O(log n) multiplications |
| Euclid's gcd | O(log min(a, b)) |
| Digit loop | O(number of digits) = O(log n) |
| Max points on a line | O(n²) pairs with a slope map per anchor |
25 Math & Geometry problems
Easiest first. Problems marked Free can be solved without Pro.
- 1Collapse to a Single DigitFreeEasy
- 2Widest Common TileFreeEasy
- 3Primes Below a LimitFreeEasy
- 4Zeros at the End of a FactorialEasy
- 5Add Numbers Written as TextEasy
- 6Write It in Another BaseEasy
- 7Spreadsheet Column LabelEasy
- 8Grid Posts Along a FenceEasy
- 9Modular Power by SquaringMedium
- 10Power With a Written-Out ExponentMedium
- 11Coprime CompanionsMedium
- 12Divisible by Any of ThreeMedium
- 13Next Arrangement of DigitsMedium
- 14Digit on the Counting RibbonMedium
- 15Multiply Numbers Written as TextMedium
- 16Area Under Two TarpsMedium
- 17Four Stakes Make a SquareMedium
- 18Total of a Fraction ExpressionMedium
- 19Sensors Inside a Triangular ZoneMedium
- 20Rectangles From Survey MarkersMedium
- 21Primes in a Far WindowHard
- 22Tally a Digit From One to NHard
- 23Long Division on Text NumbersHard
- 24Most Lamps on One Straight LineHard
- 25Hidden Grid Points in a PlotHard
Solve them in the browser, in Python or JavaScript.