Problem 372

Abstract / Summary

Given a large exponent as a digit string and a base number compute the last digit of the base raised to that large exponent.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0372.py

class Solution:
    def superPow(self, a: int, b: List[int]) -> int:
        # nothing's forbidden, therefore Python should do the hard work ;-)
        exponent = 0
        for x in b:
            exponent *= 10
            exponent += x

        return pow(a, exponent, 1337) # it's powmod
9 lines | 301 bytes | submitted August 20, 2023 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (200k+ submissions).

Typical patterns to solve this problem:
  • Divide And Conquer
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method superPow. The method receives an integer base a and a list of digits b that together represent a large exponent. The core responsibility of the method is to compute (a^{\text{exponent}} \bmod 1337) where the exponent is reconstructed from the digit list. The solution relies on Python’s built-in arbitrary-precision arithmetic and the three-argument form of pow to perform modular exponentiation efficiently.

Key Steps

Reconstructing the exponent

The first logical block iterates over the digit list b and builds the integer value of the exponent. The code initializes a variable exponent to zero. For each digit x in b, the current value of exponent is multiplied by ten and then the digit x is added. This mimics the manual conversion of a decimal representation stored as separate digits into a single integer.

exponent = 0
for x in b:
    exponent *= 10
    exponent += x

Performing modular exponentiation

After the exponent has been assembled, the method returns the result of pow(a, exponent, 1337). The three-argument version of pow computes the power under a modulus using an efficient algorithm (binary exponentiation) that avoids constructing the potentially astronomically large intermediate value of a**exponent. The constant modulus 1337 is hard-coded as required by the problem specification.

return pow(a, exponent, 1337)  # it's powmod

Edge Cases Handled

When the digit list b is empty, the loop that builds the exponent never executes, leaving exponent at its initial value of zero. Consequently the method computes pow(a, 0, 1337), which correctly yields 1 modulo 1337 for any non-zero base, matching the mathematical definition of any number raised to the zero power.

If the list b contains leading zeros, the multiplication-by-ten step preserves those zeros in the positional value, ensuring that the exponent reflects the exact decimal number intended by the digit sequence.

The use of Python’s built-in pow automatically accommodates very large values of a and exponent. Even when exponent exceeds typical integer limits, the modular exponentiation algorithm processes the bits of the exponent without overflow, delivering a correct result modulo 1337.

Performance Optimizations

The most significant optimization is the delegation of the heavy lifting to Python’s native pow function with three arguments. This built-in routine implements modular exponentiation using exponentiation by squaring, which reduces the number of multiplications dramatically compared to naïve repeated multiplication. By invoking pow directly, the code avoids explicit loops for exponentiation and benefits from the interpreter’s highly tuned C implementation.

Another subtle optimization lies in the construction of the exponent. By updating exponent in place with multiplication and addition, the code avoids creating intermediate strings or performing costly conversions. The arithmetic operations are performed on Python’s native integer type, which is optimized for large numbers and scales well with the size of the digit list.

Overall, the combination of in-place exponent reconstruction and the use of a built-in modular exponentiation routine yields a solution that runs efficiently even when the digit list represents an exponent with hundreds of digits.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big treasure box, and you want to pack it with lots of stars based on a special secret number. The first part of this code looks at a long list of numbers that act like a giant instructions manual for how many stars to add. It reads each number one by one and stitches them together to build one very large number. Think of it like putting together a long train made of individual blocks. Once the train is built, the code uses a magical math tool to figure out how many stars fit in the box. This tool takes the starting number and multiplies it over and over again until it reaches the total count from the long train. Because the number can get incredibly huge, the tool keeps everything tidy by only keeping track of the remainder whenever the pile gets bigger than thirteen hundred thirty-seven. It treats that special number like a fence and starts over every time it hits it to keep the counting easy.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.37 | σ = 2.18

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
halfrost Go
JoshCrozier JS
linouk23 Python
lkwq007 Python
lzl124631x C++
qiyuangong Python
ruoru Rust
suxrobGM C#
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
halfrost Go
JoshCrozier JavaScript
linouk23 Python
lkwq007 Python
lzl124631x C++
qiyuangong Python
ruoru Rust
suxrobGM C#
zfang399 C++
30 links | 17 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 1 medium
5 solutions   August 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality