Problem 1780

Abstract / Summary

Check if a number can be written as a sum of distinct powers of three.

Note

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

Python 1780.py

class Solution:
    def checkPowersOfThree(self, n: int) -> bool:
        while n > 0:
            if n % 3 == 2:
                return False
            n //= 3
        return True
7 lines | 190 bytes | submitted January 1, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (200k+ submissions).

Typical patterns to solve this problem:
  • 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 provided Solution class implements a method checkPowersOfThree that determines whether a non-negative integer n can be expressed as a sum of distinct powers of three. In other words, it checks if the base-3 representation of n contains only the digits 0 or 1. The algorithm iteratively examines each ternary digit of n from the least significant position, returning False immediately when a digit 2 is encountered, and True when the entire number has been processed without finding such a digit.

Core Logic

The method uses a while loop that continues as long as n remains greater than zero. Inside the loop, the remainder of n divided by three is inspected:

if n % 3 == 2:
    return False

If the remainder equals 2, the current ternary digit is 2, which violates the condition that only digits 0 and 1 are allowed. The function therefore returns False at this point, terminating the computation early.

When the remainder is not 2, the number is reduced by integer division by three:

n //= 3

This operation discards the least significant ternary digit that has just been examined and shifts the next digit into the least significant position for the following iteration.

After the loop finishes-meaning all digits have been examined without encountering a 2-the method returns True:

return True

This final return indicates that every ternary digit of the original number was either 0 or 1, confirming that n is a sum of distinct powers of three.

Edge Cases Handled

The algorithm gracefully handles the case where n is zero. Since the loop condition while n > 0 is false initially, the loop body is never executed and the method proceeds directly to the final return True. This correctly reflects that zero can be represented as an empty sum of powers of three.

Another implicit edge case is the handling of very large integers. Python’s arbitrary-precision integer arithmetic ensures that the modulo and floor-division operations work correctly regardless of the magnitude of n. The loop will iterate once per ternary digit, terminating when all digits have been processed.

Performance Optimizations

The implementation achieves early termination by returning False as soon as a disallowed digit (2) is detected. This prevents unnecessary processing of the remaining higher-order digits, which can be significant for numbers that contain a 2 in a low-order position.

The use of integer division (//) to shift the number eliminates the need for explicit string conversion or array manipulation of the ternary representation. This keeps the memory footprint minimal, as the algorithm operates directly on the integer value without allocating auxiliary data structures.

By relying on simple arithmetic operations (% and //) inside a tight loop, the method benefits from the highly optimized low-level implementation of these operators in the Python runtime, contributing to fast execution for the typical range of input values.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a magical game where you have a big pile of puzzle pieces with different shapes. Some pieces have three blocks, some have nine, some have twenty-seven, and so on. The goal is to figure out if you can build a specific number by picking some of these pieces, but you can only use each size of piece one time.

Think of the number you are looking at as a stack of blocks. To check if it works, you keep dividing the pile into groups of three. If you ever find a group that has a remainder of two blocks left over after dividing, it means that piece size cannot be used to build that total, and the answer is no. If you keep dividing until all the blocks are gone and you never had that pesky remainder of two, then you have successfully found a way to build the number using those special puzzle pieces, and the answer is yes.

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 = 9 | μ = 8.74 | σ = 0.89

Complexity Analysis

Time: 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 C# Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
trung-hn Python
28 links | 15 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 1, 2024

Fun Facts

This is my highest quality solution (medium) with an average rating of 8.7.

1 fun fact

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