Problem 1363

Abstract / Summary

Given a list of digits, create the largest possible number using some of the digits that is a multiple of three by removing the fewest digits.

Note

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

Python 1363.py

class Solution:
    def largestMultipleOfThree(self, digits: List[int]) -> str:
        # count digits
        digitsum = 0
        freq     = [ 0 ] * 10
        for d in digits:
            freq[d]  += 1
            digitsum += d

        error = digitsum % 3
        # remove one digit
        for i in range(1, 10):
            if error != 0 and i % 3 == error and freq[i] > 0:
                freq[i] -= 1
                error    = 0
                break

        # need to remove two digits
        if error != 0:
            for i in range(1, 10):
                # any small digits which are not multiples of three
                while freq[i] > 0 and i % 3 != 0 and error != 0:
                    freq[i] -= 1
                    error   -= i % 3
                    if error < 0:
                        error += 3

        result = ""
        if error == 0:
            for i in range(9, 0, -1):
                result += str(i) * freq[i]
            if freq[0] > 1 and not result:
                return "0" # not multiple zeros
            result += "0" * freq[0]

        return result
36 lines | 1139 bytes | submitted October 30, 2023 | GitHub   17% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 33% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
  • Math
  • Sorting
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 implementation builds the largest possible integer, represented as a string, that can be formed from a list of decimal digits and is divisible by three. It first records the frequency of each digit, computes the total sum, and then adjusts the digit multiset so that the sum becomes a multiple of three. Finally it assembles the result in descending order, taking care of special cases involving zeros.

Counting Digits and Computing the Sum

The algorithm begins by initializing a frequency array for the ten possible digit values and a running total of the digit sum.

digitsum = 0
freq     = [ 0 ] * 10
for d in digits:
    freq[d]  += 1
    digitsum += d

This single pass over the input list simultaneously gathers the count of each digit and the aggregate sum, which is essential for the divisibility check.

Determining the Remainder Modulo Three

The remainder of the total sum when divided by three dictates whether any digits must be removed.

error = digitsum % 3

If error equals zero, the current multiset already satisfies the divisibility condition and no removal is needed.

Removing a Single Digit When Possible

When the remainder is non-zero, the code first attempts to eliminate a single digit whose own remainder matches the overall remainder. It scans the digits from smallest to largest, ensuring that the smallest possible digit is removed to preserve the magnitude of the final number.

for i in range(1, 10):
    if error != 0 and i % 3 == error and freq[i] > 0:
        freq[i] -= 1
        error    = 0
        break

The early break stops the loop as soon as a suitable digit is found, preventing unnecessary iterations.

Removing Two Digits When a Single Removal Is Insufficient

If the single-digit removal does not resolve the remainder, the algorithm proceeds to discard two digits whose combined remainders offset the error. It iterates again from the smallest digit upward, repeatedly removing eligible digits until the remainder is cleared.

if error != 0:
    for i in range(1, 10):
        while freq[i] > 0 and i % 3 != 0 and error != 0:
            freq[i] -= 1
            error   -= i % 3
            if error < 0:
                error += 3

The inner while loop allows removal of multiple instances of the same digit, and the conditional adjustment of error ensures it stays within the range [0,2].

Constructing the Result String in Descending Order

After the frequency array reflects a digit set whose sum is a multiple of three, the code concatenates the digits from nine down to one, repeating each digit according to its remaining count.

result = ""
if error == 0:
    for i in range(9, 0, -1):
        result += str(i) * freq[i]

Appending the zeros follows, but only after handling a special case where the result would otherwise be empty.

Handling the All-Zero Edge Case

When the only digits left are zeros, the algorithm must return a single "0" rather than a string of multiple zeros. This situation is detected by checking that no non-zero digits have been added to result while there are at least two zeros available.

    if freq[0] > 1 and not result:
        return "0"
    result += "0" * freq[0]

If exactly one zero remains, it is appended to the result, yielding "0" as well. The condition freq[0] > 1 prevents returning "00" or longer strings of zeros, which would be numerically equivalent but not the canonical representation.

Returning the Final String

The function concludes by returning the assembled string. If the remainder could not be eliminated (which would happen only if the input lacked sufficient digits to adjust the sum), the result remains empty and the function returns an empty string.

return result

Implicit Performance Optimizations

The use of a fixed-size frequency array eliminates the need for dynamic data structures, providing constant-time access for counting and updating digit occurrences. The algorithm performs a single linear scan to build the frequency table, followed by at most two additional linear scans over the ten possible digit values, resulting in a predictable and low overhead regardless of input size. Early termination in the single-digit removal loop and the bounded inner while loop further reduce unnecessary work, especially when the required adjustments are minimal. The final string construction leverages Python’s ability to repeat strings (str(i) * freq[i]), which is more efficient than concatenating individual characters in a loop.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a bucket full of colorful number blocks and wanting to build the biggest tower possible that follows a secret rule. The rule is that the total value of the blocks in the tower must be a special number that divides perfectly into three piles.

To solve this, first place all the number blocks into little slots based on which number they are. Keep track of the total sum of all those numbers combined. Sometimes the sum is not quite right and will not divide into three piles evenly. To fix that, look for one little block that makes the total sum behave correctly when taken away. By removing that one pesky block, the rest of the numbers will add up perfectly.

If removing just one block is not enough to make the total sum work out, look for two smaller blocks to take out instead. This shifts the total around until it finally obeys the rule. After the right blocks have been removed, arrange all the remaining blocks from the biggest ones down to the smallest ones to make the longest tower possible. If there are any big zeros left over, tuck them in at the bottom to make the tower even taller. Once the blocks are all sorted and the ones that do not fit have been left out, the remaining line of numbers is the biggest, best result.

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 | μ = 6.26 | σ = 1.55

Complexity Analysis

Time: linear
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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
gouthampradhan Java
JoshCrozier JS
lkwq007 Python
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
lkwq007 Python
wisdompeak C++
23 links | 12 authors | 6 languages

Videos

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

Solved On The Same Day

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