Cracking the Code: Is It a Power of Three? (LeetCode 326 Deep Dive!) 🤯
Hey there, future coding legends! 👋 Vansh2710 here, ready to tackle another fun LeetCode challenge that might seem simple on the surface but has some neat tricks up its sleeve. Today, we're diving into Problem 326: Power of Three.
This problem is a fantastic way to practice handling edge cases, understanding numerical properties, and even thinking about optimization. Let's get started!
The Problem: What Exactly Are We Looking For? 🤔
We're given an integer n. Our task is to determine if n is a "power of three."
What does "power of three" mean?
It means n can be expressed as 3 raised to some integer exponent x (i.e., n == 3^x).
Let's look at the examples:
-
Example 1:
n = 27- Is
27a power of three? Yes!27 = 3 * 3 * 3 = 3^3. So, we should returntrue.
- Is
-
Example 2:
n = 0- Is
0a power of three? No. There's no exponentxfor which3^xequals0.3^0 = 1,3^1 = 3,3^-1 = 1/3, etc. So, we should returnfalse.
- Is
-
Example 3:
n = -1- Is
-1a power of three? No. Powers of positive numbers (like 3) are always positive. So, we should returnfalse.
- Is
Key Constraints:
n will be between -2^31 and 2^31 - 1. This is the typical range for a 32-bit signed integer.
The "Aha!" Moment: How Do We Spot a Power of Three? ✨
Imagine you have a number, say 81. How would you manually check if it's a power of three?
You'd probably do something like this:
- Is
81divisible by3? Yes,81 / 3 = 27. - Is
27divisible by3? Yes,27 / 3 = 9. - Is
9divisible by3? Yes,9 / 3 = 3. - Is
3divisible by3? Yes,3 / 3 = 1. - We reached
1! This means81is indeed a power of three (3^4).
What if we had 28?
- Is
28divisible by3? No!28 % 3 = 1. Since we can't divide it evenly by 3 and reach 1,28is not a power of three.
This repeated division gives us a strong hint! However, instead of repeatedly dividing, we can also multiply powers of three and see if we hit n. This is the intuition behind the provided solution. We'll start with 1 (which is 3^0) and keep multiplying by 3, checking if we ever reach n.
Step-by-Step Approach 🚀
Let's break down the strategy used in the solution:
-
Handle Non-Positive Numbers:
- As seen in Example 2 (
n=0) and Example 3 (n=-1), any number less than or equal to0cannot be a power of three. So, our very first check should be:if (n <= 0) return false;.
- As seen in Example 2 (
-
Handle the Base Case (n = 1):
-
1is3^0. It's a power of three. So,if (n == 1) return true;. This is an important edge case to handle explicitly to avoid issues in the multiplication loop.
-
-
Iterative Multiplication:
- We need a variable, let's call it
res(for "result"), to store increasing powers of three. Initializeres = 1(since3^0 = 1). - Now, we'll start a loop. In each iteration, we multiply
resby3. - After each multiplication, we check if
resis equal ton. If it is,nis a power of three, and we can immediately returntrue.
- We need a variable, let's call it
-
Why
long longforresand a loop for30iterations?- The maximum
intvalue is2^31 - 1(approx2 * 10^9). - The largest power of three that fits in a positive
intis3^19 = 1,162,261,467. -
3^20would already exceed2^31 - 1. - To avoid potential overflow issues if
nis large (andresmight temporarily exceedintmax before matchingn), it's safer to uselong longforres. This ensuresrescan hold values beyond theintrange if needed. - A loop running
30times is sufficient because3^19is the largest relevant power. We don't need to go much further, and3^30would certainly exceedlong longmax if we were to keep calculating without checkingres > n(which isn't strictly necessary here because we checkn == resandnis an int). The30iterations are a safe upper bound.
- The maximum
-
No Match Found:
- If the loop finishes without
never matchingres, it meansnis not a power of three. We then returnfalse.
- If the loop finishes without
The Code 🧑💻
Here's the complete C++ solution, based on the structure we discussed:
class Solution {
public:
bool isPowerOfThree(int n) {
// Step 1: Handle non-positive numbers
if (n <= 0) {
return false;
}
// Step 2: Handle the base case n = 1 (3^0)
if (n == 1) {
return true;
}
// Step 3 & 4: Iterative multiplication and check for match
// Use long long for 'res' to safely store larger powers of three
// before comparison, preventing potential overflow issues if n is large.
long long res = 1;
for (int i = 0; i < 30; i++) { // 3^19 is largest power fitting in int, 30 iterations is safe
res = res * 3; // Calculate the next power of three
// If current power of three matches n, we found our answer!
if (n == res) {
return true;
}
// Optimization: If 'res' becomes larger than 'n',
// 'n' cannot be a power of three because powers of three only grow.
// This also helps prevent 'res' from overflowing if n is not a power of 3.
if (res > n) {
return false;
}
}
// Step 5: If loop completes without a match, n is not a power of three
return false;
}
};
Time & Space Complexity Analysis ⏱️📏
-
Time Complexity: O(1)
- Why O(1)? The loop runs a fixed maximum number of times (30 iterations). It does not depend on the input
nin a way that scales withn(e.g.,nitself is not the loop bound). Performing a fixed number of operations means constant time complexity.
- Why O(1)? The loop runs a fixed maximum number of times (30 iterations). It does not depend on the input
-
Space Complexity: O(1)
- We use a few variables (
n,res,i) which take up a constant amount of memory regardless of the input valuen.
- We use a few variables (
Key Takeaways ✨
- Edge Cases are Crucial: Always consider
0, negative numbers, and the smallest positive case (1for powers of three). - Iterative Solutions: For problems involving powers, repeated multiplication or division is a very common and effective pattern.
- Preventing Overflow: Be mindful of integer limits. Using
long longfor intermediate calculations when dealing with potentially large numbers (likeres * 3) can save you from subtle bugs. - Constant Time is Awesome: When you can solve a problem in
O(1)time, you've done a great job!
This problem also has a fascinating "Follow up" question: "Could you solve it without loops/recursion?" This hints at mathematical properties (like using log functions) or leveraging the fact that the largest power of 3 that fits in an int is a known constant. We'll leave that as a thought exercise for another day! 😉
Hope this breakdown helped you understand LeetCode 326 better! Happy coding!
Authored by Vansh2710. Published on 2026-04-09 23:43:07.
Top comments (0)