Leetcode #372: Super Pow
In this guide, we solve Leetcode #372 Super Pow in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example 1: Input: a = 2, b = [3] Output: 8 Example 2: Input: a = 2, b = [1,0] Output: 1024 Example 3: Input: a = 1, b = [4,3,3,8,5,2] Output: 1 Constraints: 1 <= a <= 231 - 1 1 <= b.length <= 2000 0 <= b[i] <= 9 b does not contain leading zeros.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Divide and Conquer
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: a = 2, b = [3]
Output: 8
Python Solution
class Solution:
def superPow(self, a: int, b: List[int]) -> int:
mod = 1337
ans = 1
for e in b[::-1]:
ans = ans * pow(a, e, mod) % mod
a = pow(a, 10, mod)
return ans
Complexity
The time complexity is O(n) or O(1). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.