Advertisement

Power of Three - LeetCode 326 Solution

Power of Three - Complete Solution Guide

Power of Three is LeetCode problem 326, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given an integer n , return true if it is a power of three. Otherwise, return false . An integer n is a power of three, if there exists an integer x such that n == 3 x . Example 1: Input: n = 27 Output: true Explanation: 27 = 3 3 Example 2: Input: n = 0 Output: false Explanation: There is no x where 3 x = 0. Example 3: Input: n = -1 Output: false Explanation: There is no x where 3 x = (-1). Constraints: -2 31 <= n <= 2 31 - 1 Follow up: Could you solve it without loops/recursion?

Detailed Explanation

The problem asks to determine if a given integer `n` is a power of three. This means checking if there exists an integer `x` such that 3 raised to the power of `x` equals `n`. The input is an integer `n`, and the output is a boolean value: `true` if `n` is a power of three, and `false` otherwise. The input integer is constrained to be within the range of a 32-bit integer.

Solution Approach

The provided solution uses an iterative approach. It first checks if the input `n` is less than or equal to 0. If it is, it immediately returns `false` because powers of three are always positive. Otherwise, it enters a `while` loop that continues as long as `n` is divisible by 3. Inside the loop, `n` is repeatedly divided by 3 using integer division. Finally, the function checks if `n` is equal to 1. If it is, it means that the original number was a power of three; otherwise, it wasn't.

Step-by-Step Algorithm

  1. Step 1: Check if `n` is less than or equal to 0. If true, return `false`.
  2. Step 2: Enter a `while` loop that continues as long as `n` is divisible by 3 ( `n % 3 == 0`).
  3. Step 3: Inside the loop, divide `n` by 3 using integer division (`n //= 3` or `n /= 3`).
  4. Step 4: After the loop, check if `n` is equal to 1. If true, return `true`; otherwise, return `false`.

Key Insights

  • Insight 1: Repeatedly dividing by 3: If a number is a power of three, repeatedly dividing it by 3 will eventually result in 1. If at any point the remainder is not 0, it's not a power of three.
  • Insight 2: Handling negative numbers and zero: Powers of three are always positive integers. Negative numbers and zero cannot be powers of three.
  • Insight 3: Efficient modulo and division operations: Using modulo (%) and integer division (// or /) operations is efficient for repeatedly checking divisibility by 3.

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(1)

Topics

This problem involves: Math, Recursion.

Companies

Asked at: Goldman Sachs.