#372
Super Pow
MediumMathDivide and ConquerDivide and ConquerModular Arithmetic
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of converting b into a single integer, we can use properties of modular arithmetic and the fact that we can break down the exponentiation into smaller parts using the modulus operation.
⚙️
Algorithm
3 steps- 1Step 1: Define a helper function to compute (a^b) % 1337 using modular exponentiation.
- 2Step 2: For each digit in b, recursively calculate (a^(b[i]) % 1337) and combine results using the formula: (a^(10 * prev) % 1337) * (a^(b[i]) % 1337).
- 3Step 3: Return the final result.
solution.py14 lines
1# Full working Python code
2
3def superPow(a, b):
4 def modPow(x, n):
5 if n == 0:
6 return 1
7 half = modPow(x, n // 2)
8 return (half * half * (x if n % 2 else 1)) % 1337
9
10 result = 1
11 for digit in reversed(b):
12 result = result * modPow(a, digit) % 1337
13 a = modPow(a, 10)
14 return resultℹ
Complexity note: The time complexity is O(n) because we iterate through the array b once and perform constant time operations for each digit.
- 1Using modular exponentiation helps manage large numbers effectively.
- 2Breaking down the exponentiation into smaller parts allows for efficient calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.