Problem 1414

Abstract / Summary

Given a number k find the smallest count of fibonacci numbers that add up to k

Note

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

Python 1414.py

class Solution:
    def findMinFibonacciNumbers(self, k: int) -> int:
        # generate Fibonacci sequence
        fib = [ 1, 1 ]
        while fib[-1] < k:
            fib.append(fib[-2] + fib[-1])

        # subtract largest elements of that sequence
        steps = 0
        while k > 0:
            if fib[-1] <= k:
                k     -= fib[-1]
                steps += 1
            fib.pop()
        return steps
15 lines | 440 bytes | submitted November 10, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Greedy
  • 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 implementation solves the classic “minimum number of Fibonacci numbers whose sum equals a given integer k” problem. It follows a two-phase approach: first it builds the Fibonacci sequence up to the target value, then it repeatedly subtracts the largest possible Fibonacci number from the remaining amount. The count of subtractions is returned as the answer.

Generation of Fibonacci Sequence

The algorithm begins by constructing a list that holds the Fibonacci numbers needed for the greedy phase. It starts with the two initial values 1, 1 and extends the list while the last element remains smaller than the target k.

fib = [1, 1]
while fib[-1] < k:
    fib.append(fib[-2] + fib[-1])

Because the loop condition checks the most recent element against k, the list stops exactly when the next Fibonacci number would exceed k. This ensures the sequence contains every candidate that could contribute to the sum without unnecessary extra elements.

Greedy Subtraction Loop

After the sequence is ready, the method enters a second loop that reduces k by the largest feasible Fibonacci number at each step. The loop continues until k becomes zero. Inside the loop, a comparison determines whether the current largest Fibonacci number (fib[-1]) can be used. If it fits, k is decreased and the step counter is incremented. Regardless of the comparison outcome, the largest element is removed from the list, guaranteeing progress toward termination.

steps = 0
while k > 0:
    if fib[-1] <= k:
        k     -= fib[-1]
        steps += 1
    fib.pop()
return steps

The greedy choice is justified by the mathematical property that any integer can be expressed as a sum of non-consecutive Fibonacci numbers (Zeckendorf’s theorem). By always picking the biggest possible term, the algorithm automatically produces the minimal count.

Edge Cases Handled

When k equals 1, the initial list already contains the needed value, the second loop subtracts it in the first iteration, and the function returns 1. If k itself is a Fibonacci number, the first comparison in the greedy loop succeeds immediately, reducing k to zero in a single step, which correctly yields the minimal count of 1. For values of k that are not Fibonacci numbers, the loop iteratively selects decreasing terms until the remainder is exhausted, guaranteeing that the algorithm never attempts to subtract a number larger than the remaining k. The while fib[-1] < k generation guard also prevents an infinite loop when k is very small, because the list will contain at least the two initial ones.

Performance Optimizations

The code limits the size of the Fibonacci list to the smallest set that can represent k. By stopping the generation as soon as the next Fibonacci number would exceed k, it avoids allocating or processing superfluous elements. The use of fib.pop() in the greedy phase removes the need for an explicit index variable; each iteration discards the largest candidate, ensuring constant-time access to the next value. This in-place reduction of the list eliminates extra bookkeeping and keeps the inner loop tight. Additionally, the algorithm performs only integer arithmetic and simple list operations, which are highly efficient in Python’s runtime environment.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of building blocks where each size is the sum of the two sizes before it. This turns into a special pattern that starts with one, one, two, three, five, and eight. The code first builds a tall tower of these blocks that reaches higher than the number k, which is the target goal.

Once the tower is ready, the code looks at the biggest block at the very top. If that block is smaller than the target number, it puts that block to the side and subtracts its size from the target. It keeps doing this, checking the next biggest block and taking it away if it fits, until the target reaches zero. Every time it successfully takes a block away, it adds one to a counter. The whole process is like trying to reach a specific height by picking out the fewest number of special blocks possible.

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 = 8 | μ = 7.52 | σ = 1.23

Complexity Analysis

not analyzed yet

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 Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
wisdompeak C++
YuriSpiridonov Python
28 links | 16 authors | 9 languages

Videos

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

Solved On The Same Day

5 solutions   November 10, 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