MediumNo. 0372

Super Pow — LeetCode 372 Python Solution

Topics
Math, Divide and Conquer
Reading time
2 min

The problem

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

Input
a = 2, b = [3]
Output
8

Python solution

PythonSolution
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

Time
O(n) or O(1)
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 372. Super Pow is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0932Beautiful ArrayMedium
0382Linked List Random NodeMedium
0002Add Two NumbersMedium
0007Reverse IntegerMedium
0009Palindrome NumberEasy
0043Multiply StringsMedium

Frequently asked questions

How hard is LeetCode 372. Super Pow?

LeetCode 372. Super Pow is rated Medium on LeetCode.

What topics does LeetCode 372. Super Pow cover?

LeetCode 372. Super Pow is tagged Math and Divide and Conquer on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.