Three Fibonacci Sum Problem
Description
LeetCode Problem 4078.
You are given an integer n.
The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. Its first few terms are 0, 1, 1, 2, 3, 5, 8, 13, ....
Return true if n can be expressed as the sum of three consecutive terms in the Fibonacci sequence, and false otherwise.
Example 1:
Input: n = 16
Output: true
Explanation:
The three consecutive terms 3, 5, and 8 have a sum of 3 + 5 + 8 = 16.
Example 2:
Input: n = 8
Output: false
Explanation:
Although 1 + 2 + 5 = 8, these terms are not consecutive in the Fibonacci sequence. No three consecutive terms have a sum of 8.
Example 3:
Input: n = 2
Output: true
Explanation:
The first three terms have a sum of 0 + 1 + 1 = 2.
Constraints:
1 <= n <= 10^9
Solution
Approach: Fibonacci lookup
Three consecutive terms satisfy F(i) + F(i+1) + F(i+2) = 2 * F(i+2), because F(i) + F(i+1) = F(i+2). As i runs over 0, 1, 2, ..., F(i+2) takes every Fibonacci value from 1 upward.
So n is such a sum exactly when n is even and n / 2 is a Fibonacci number at least 1. Generate all Fibonacci numbers up to 10^9 once, keep them in a set, and test n / 2.
Complexity: O(log M) preprocessing (M = 10^9), then O(1) per query.
a, b = 0, 1
mx = 10**9 + 1
f = set()
while b < mx:
a, b = b, a + b
f.add(b)
class Solution:
def threeFibonacciSum(self, n: int) -> bool:
return n % 2 == 0 and n // 2 in f