Matrix rotation, spiral order, number tricks, and fast exponentiation.
Reach for it when
Transform a matrix in place
Digit manipulation, overflow, big numbers as strings
Power, modulo, or cycle detection in number sequences
Core idea
Many of these reduce to a known identity: rotating a matrix 90 degrees clockwise is transpose then reverse each row; x^n is computed by squaring (n halves each step); spiral order peels the boundary layer by layer with four shrinking bounds.
Template · O(log n) for fast power; O(n²) for an n by n matrix
defmy_pow(x, n):
if n <0:
x, n =1/ x, -n
result =1
while n:
if n &1:
result *= x
x *= x # square the base
n >>=1# halve the exponent
return result
doublemyPow(doublex, longlongn) {
if (n <0) { x =1/ x; n =-n; } // long long: -INT_MIN overflows int
double result =1;
while (n) {
if (n &1) result *= x;
x *= x; // square the base
n >>=1; // halve the exponent
}
return result;
}
Common pitfalls
Negative exponents and integer overflow in other languages
Spiral bounds: re-check top and bottom (or left and right) before the return passes