372. Super Pow
At a Glance
- Topic: math-geometry
- Pattern: Modular exponentiation (Divide & Conquer)
- Difficulty: Medium
- Companies: Amazon, Google, Facebook, ByteDance, Airbnb
- Frequency: Low
- LeetCode: 372
Problem (one-liner)
Compute base ** exponent mod 1337 where exponent is given as an array of decimal digits (most significant first), representing a large positive integer.
Recognition Cues
- Huge exponent — cannot materialize as integer
- "Super pow" / digit array exponent
- Fixed modulus
1337
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — impossible exponent range.
- Optimal — recursive relation:
pow(a, [b0..bk]) = pow(a, [b0..b_{k-1}])**10 * pow(a, bk) (mod m)—O(len * log base)modular multiplies.
Optimal Solution
Go
package main
const modulus = 1337
func superPow(base int, exponent []int) int {
if len(exponent) == 0 {
return 1
}
lastDigit := exponent[len(exponent)-1]
prefix := exponent[:len(exponent)-1]
part := superPow(base, prefix)
part = modPow(part, 10, modulus)
part = part * modPow(base, lastDigit, modulus) % modulus
return part
}
func modPow(base int, exponent int, mod int) int {
result := 1
base = base % mod
for exponent > 0 {
if exponent%2 == 1 {
result = result * base % mod
}
base = base * base % mod
exponent /= 2
}
return result
}JavaScript
const MODULUS = 1337;
function superPow(base, exponent) {
if (exponent.length === 0) {
return 1;
}
const lastDigit = exponent[exponent.length - 1];
const prefix = exponent.slice(0, -1);
let part = superPow(base, prefix);
part = modPow(part, 10, MODULUS);
part = (part * modPow(base, lastDigit, MODULUS)) % MODULUS;
return part;
}
function modPow(base, exponent, mod) {
let result = 1;
base = base % mod;
while (exponent > 0) {
if (exponent % 2 === 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exponent = Math.floor(exponent / 2);
}
return result;
}Walkthrough
Exponent digits [1, 2] means decimal 12. Decompose: a**12 = (a**1)**10 * a**2 (mod m) after processing prefix [1].
Invariant: each recursive call reduces digit-array length by one while preserving modular value.
Edge Cases
- Exponent array
[0]→ returns1 mod 1337 baselarger than modulus — reduce insidemodPow
Pitfalls
- Forgetting to
% modafter intermediate multiplications - Wrong order combining
**10and last-digit power
Similar Problems
- 050. Pow(x, n) — same binary exponentiation core.
- 043. Multiply Strings — manual multi-precision operations.
Variants
- Change modulus to prime and use Euler theorem (when coprime).
- Exponent given in another base.
Mind-Map Tags
#modular-exponentiation #super-pow #digit-array #recurrence #math
Last updated on
Spotted something unclear or wrong on this page?