Problem 970

Abstract / Summary

Given two positive integers and a bound, find all unique sums of powers of those integers that are less than or equal to the bound.

Note

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

Python 0970.py

class Solution:
    def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
        result = set()

        xx = 1
        while xx <= bound:
            yy = 1
            while xx + yy <= bound:
                result.add(xx + yy)
                yy *= y
                if y == 1:
                    break

            xx *= x
            if x == 1:
                break

        return result
18 lines | 430 bytes | submitted October 7, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (100k+ submissions).

Typical patterns to solve this problem:
  • Enumeration
  • Hash Table
  • 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 powerfulIntegers method generates all distinct integers that can be expressed as xⁱ + yʲ where i and j are non-negative integers, and the sum does not exceed the supplied bound. The result is returned as a set, guaranteeing uniqueness of the values.

Initialization

At the start a Python set named result is created to collect the qualifying sums. Two accumulator variables, xx and yy, are introduced to hold the current powers of x and y respectively. Both are seeded with 1, representing x⁰ and y⁰.

result = set()
xx = 1

Outer Loop Over Powers of x

The outer while loop iterates as long as the current power of x (xx) remains within the bound. Inside this loop the inner loop explores all feasible powers of y for the current xx. After the inner loop finishes, xx is multiplied by x to move to the next exponent. A special guard if x == 1: break stops further multiplication when x equals 1, because repeated multiplication would otherwise produce an infinite series of identical values.

while xx <= bound:
    # inner loop runs here
    xx *= x
    if x == 1:
        break

Inner Loop Over Powers of y

For each fixed xx, the inner while loop walks through powers of y. It starts with yy = 1 and continues while the sum xx + yy does not exceed bound. Each valid sum is added to result. After adding, yy is multiplied by y to advance to the next exponent. When y equals 1, the loop breaks after the first iteration because further multiplication would not change yy, preventing an endless loop.

yy = 1
while xx + yy <= bound:
    result.add(xx + yy)
    yy *= y
    if y == 1:
        break

Edge Cases Handled

The implementation explicitly checks for the cases where x or y is 1. In those scenarios the corresponding loop would otherwise never progress, as multiplying by 1 leaves the accumulator unchanged. The break statements ensure that the algorithm terminates correctly after processing the single meaningful value (1).

When bound is smaller than the smallest possible sum (2 when both x and y are at least 1), the outer loop condition xx <= bound fails immediately, resulting in an empty set, which correctly reflects that no powerful integers exist within the given limit.

If either x or y is 0, the multiplication steps would produce 0 after the first iteration, but the loop conditions still enforce the bound check, so only sums that respect the limit are added. The early break for the base-case 1 also prevents unnecessary iterations when the other base is 0.

Performance Optimizations

The algorithm avoids redundant calculations by storing results in a set, which automatically discards duplicate sums that can arise when different exponent pairs produce the same value (for example, when x and y are both 2).

The loop bounds are tightly controlled: the outer loop stops as soon as xx exceeds bound, and the inner loop stops when xx + yy would exceed bound. This prevents the exploration of exponent combinations that cannot possibly satisfy the constraint, reducing the number of iterations dramatically for large bound values.

The explicit break statements for the cases x == 1 and y == 1 act as early exits, eliminating the need for additional checks inside the loops and preventing infinite cycles. By updating xx and yy through multiplication rather than exponentiation functions, the code leverages integer arithmetic that is fast and avoids the overhead of function calls.

Overall, the nested while-loop structure combined with the early termination conditions yields an efficient enumeration of all valid powerful integers within the specified bound.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two different magic building blocks. One block grows by multiplying itself by the number x over and over, and the other grows by multiplying itself by the number y. The goal of this code is to find all the different numbers you can make by adding one of these blocks to the other, as long as the total isn't bigger than your toy box, which is called the bound.

First, the code creates an empty box called result to keep track of the magic numbers it finds. Then, it starts a loop to keep picking a size for the first block. It begins with the size of one and keeps multiplying it by x until it gets too big for the toy box. Inside that loop, it starts another loop for the second block. It also starts at one and keeps multiplying the size by y until the sum of the two blocks is too big for the toy box.

Every time a combination fits inside the box, the code puts that sum into the result box. Because the result box is a special kind of container called a set, it automatically makes sure there are no duplicate numbers inside. If the block size is one, the code stops multiplying so it doesn't get stuck in a loop that never ends. Once all the possible combinations are checked, the code finishes its work.

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 | μ = 7.15 | σ = 1.48

Complexity Analysis

Time: double logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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 JS Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
33 links | 19 authors | 7 languages

Videos

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

Solved On The Same Day

3 easy 4 medium 1 hard
9 solutions   October 7, 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