Powerful Integers — LeetCode 970 Python Solution

MediumHash TableMathEnumeration
Problem
#970
Reading time
3 min

The problem

Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound. An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.

Example

Input
x = 2, y = 3, bound = 10
Output
[2,3,4,5,7,9,10]
Explanation
2 = 20 + 30

Python solution

Python
class Solution:
    def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
        ans = set()
        a = 1
        while a <= bound:
            b = 1
            while a + b <= bound:
                ans.add(a + b)
                b *= y
                if y == 1:
                    break
            if x == 1:
                break
            a *= x
        return list(ans)

Complexity

MeasureComplexity
TimeO(\log^2 bound)
SpaceO(\log^2 bound) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 970. Powerful Integers is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

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

Related problems

Frequently asked questions

How hard is LeetCode 970. Powerful Integers?
LeetCode 970. Powerful Integers is rated Medium on LeetCode.
What is the time complexity of LeetCode 970. Powerful Integers?
The Python solution on this page runs in O(\log^2 bound).
What is the space complexity of LeetCode 970. Powerful Integers?
The Python solution on this page uses O(\log^2 bound) auxiliary space.
What topics does LeetCode 970. Powerful Integers cover?
LeetCode 970. Powerful Integers is tagged Hash Table, Math and Enumeration 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.

Get Stealth Interview