This is one of those problems where the clean idea matters more than the amount of code. For 970. Powerful Integers, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are powerfulIntegers.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Powerful Integers.
02//Memory Usage: 7.7 MB, less than 100.00% of C++ online submissions for Powerful Integers.
03
04class Solution {
05public:
06 vector<int> powerfulIntegers(int x, int y, int bound) {
07 vector<int> ans;
08 int pi = 0;
09
10 for(int i = 0; pow(x, i) + pow(y, 0) <= bound; i++){
11 if(x == 1 && pi == pow(x, i) + pow(y, 0)) break;
12 for(int j = 0; pow(x, i) + pow(y, j) <= bound; j++){
13 if(y == 1 && pi == pow(x, i) + pow(y, j)) break;
14 pi = pow(x, i) + pow(y, j);
15 if(pi <= bound &&
16 find(ans.begin(), ans.end(), pi) == ans.end()){
17 ans.push_back(pi);
18 }
19 }
20 pi = pow(x, i) + pow(y, 0);
21 }
22
23 return ans;
24 }
25};
Cost