We are given an array of integers nums. We need to find the number of subarrays whose sum is a Fibonacci number.
Approach:
- Precompute Fibonacci numbers up to a certain maximum. What should be the maximum?
The sum of a subarray can be at most the sum of all positive numbers (if there are negatives, the sum could be negative? But Fibonacci numbers are non-negative. However, note that Fibonacci sequence typically starts with 0,1,1,2,... so 0 is included. But what about negative sums? They cannot be Fibonacci because Fibonacci numbers are non-negative. So we only care about non-negative sums? Actually, the problem says "Fibonacci number", which traditionally are non-negative. But note that there is an extended definition of Fibonacci for negative indices? Typically, no. So we assume Fibonacci numbers are non-negative.
However, note that the array can have negative numbers, so the subarray sum could be negative. But then it cannot be a Fibonacci number. So we can ignore subarrays with negative sum? But wait: what about 0? 0 is a Fibonacci number (if we consider F0=0). So we must consider non-negative sums.
But the array might have both positive and negative numbers, so the sum of a subarray could be negative, zero, or positive.
Steps:
- We need to compute all subarray sums? That would be O(n^2). But n can be up to? Not specified. We must design an efficient algorithm.
However, note: The problem asks for the number of subarrays. So we need to count all contiguous subarrays [i, j] such that the sum of nums[i..j] is a Fibonacci number.
We can compute prefix sums: let P[i] = sum of nums[0..i-1] (with P[0]=0). Then the sum of subarray [i, j] is P[j+1] - P[i]. We want this difference to be a Fibonacci number.
So we need to count pairs (i, j) with i < j such that P[j] - P[i] is in the set of Fibonacci numbers (with j>i because subarray length at least 1? Actually, subarray can be of length 1? Yes, a single element is a subarray. So we consider i from 0 to n-1 and j from i+1 to n? Actually, if we use prefix sums of length n+1, then for subarray from i to j (inclusive) we have sum = P[j+1] - P[i]. So we need pairs (i, j) with i < j+1? Actually, we can let i and k be indices in the prefix array, with i < k, then subarray from i to k-1 has sum P[k] - P[i]. So we need to count all pairs (i, k) with i < k such that P[k] - P[i] is a Fibonacci number.
So we have an array of prefix sums: P[0], P[1], ..., P[n]. We want to count the number of pairs (i, k) with i < k and (P[k] - P[i]) in FibSet.
How to do that efficiently?
We can iterate over k from 1 to n (since k>i, and i goes from 0 to k-1) and for each k, we want to count how many i in [0, k-1] such that P[i] = P[k] - f for some f in FibSet.
But note: the Fibonacci numbers we consider must be non-negative? Actually, the difference P[k] - P[i] must be non-negative to be a Fibonacci number? Not necessarily: if P[k] < P[i] then the difference is negative, which cannot be a Fibonacci number (since Fibonacci numbers are non-negative). So we can ignore those pairs where P[k] < P[i] because then the difference is negative.
So for each k, we want to count the number of i in [0, k-1] such that P[i] = P[k] - f for some f in FibSet and also P[k] - f >= 0? Actually, if we require the difference to be non-negative, then we require P[k] - P[i] >= 0, which means P[i] <= P[k]. So we only consider i such that P[i] <= P[k].
But wait: what if the Fibonacci number set includes 0? Then f=0, so we need P[i] = P[k]. That is allowed and gives a subarray sum of 0, which is a Fibonacci number (if we include 0). So we must include 0 in our FibSet.
So algorithm:
Step 1: Precompute Fibonacci numbers up to a maximum. What maximum? The maximum possible subarray sum? The maximum absolute value of the prefix sums? Since we have P[k] - P[i] and we want that to be at most the maximum Fibonacci we consider. But the maximum subarray sum can be as large as the sum of all positive numbers. Let S = sum of all positive numbers in nums? Actually, if there are negative numbers, the maximum subarray sum might be less. But to be safe, we can compute the maximum possible prefix sum. The prefix sums can be as high as the cumulative sum of all positives, and as low as the cumulative sum of all negatives. But we only care about non-negative differences, so we only need Fibonacci numbers up to the maximum possible difference. The maximum difference is max(P) - min(P). But note: we only consider pairs with P[i] <= P[k], so the maximum difference is max(P) - min(P). However, if min(P) is negative, then max(P) - min(P) could be larger than max(P). But we are only interested in differences that are non-negative and at most max(P) - min(P). But note that if min(P) is negative, then for a given k, we only consider i with P[i] <= P[k]. So the maximum difference for a fixed k is P[k] - min(P) (if min(P) <= P[k]). But overall, the maximum possible difference is max_{k} (P[k] - min(P)) = max(P) - min(P). So we need Fibonacci numbers up to max(P) - min(P).
However, note that the array can be large and the numbers can be large. But the problem does not specify constraints. We must assume that the array length is moderate? If n is up to 10^5, then O(n^2) is too slow. We need an O(n) or O(n log n) solution.
Let's think about the counting: for each k, we want to count the number of i in [0, k-1] with P[i] = P[k] - f for some f in FibSet. This is equivalent to: for each f in FibSet, we want to count the number of i in [0, k-1] such that P[i] = P[k] - f.
So we can maintain a frequency map of the prefix sums we have seen so far (for indices < k). Then for each k, we iterate over all f in FibSet and add freq[P[k] - f] to the answer. But note: we must ensure that P[k] - f is in the map and that the corresponding i is less than k (which it will be because we only add prefix sums of indices < k). But also, we must consider that P[k] - f might be negative? Then it won't be in the map because we only store prefix sums that have occurred. But note: the prefix sums can be negative. So we should store all prefix sums, even negative ones? But then when we compute P[k] - f, if f is positive, then P[k] - f could be negative even if P[k] is positive. But then that negative value might be in the map? Possibly. But wait: if P[i] is negative, then P[k] - P[i] = f. But if f is a Fibonacci number (non-negative) and P[k] - P[i] = f, then P[k] = P[i] + f. Since f>=0, P[k] >= P[i]. So if P[i] is negative, then P[k] could be negative too? But then f = P[k] - P[i] = (negative) - (negative) = could be positive? Example: P[i]=-5, P[k]=-3, then f=2, which is Fibonacci. So we must consider negative prefix sums.
So we cannot ignore negative prefix sums. Therefore, we should store all prefix sums in the frequency map.
But then the issue: the set of Fibonacci numbers we precompute must be up to the maximum possible difference. The maximum difference is max(P) - min(P). If the numbers are large, this could be huge. But note: the Fibonacci numbers grow exponentially. So the number of Fibonacci numbers up to a given limit M is about O(log M). So if M is 10^18, then there are about 90 Fibonacci numbers. So we can precompute all Fibonacci numbers up to max_diff.
However, what if the array is long and the numbers are huge? Then max_diff could be huge. But note: the prefix sums are cumulative. If the array has n elements, then the maximum absolute prefix sum could be as large as n * max|nums[i]|. So if n=10^5 and |nums[i]| up to 10^9, then max_diff could be 10^14, and the number of Fibonacci numbers up to 10^14 is about 70 (since Fibonacci grows fast). So that's acceptable.
Steps:
- Compute the prefix sums P[0..n]. Let P[0]=0.
- Compute minP = min(P) and maxP = max(P). Then max_diff = maxP - minP.
- Precompute all Fibonacci numbers up to max_diff (including 0 and 1, etc). Store them in a set FibSet.
- Initialize an empty frequency map (dictionary) for prefix sums. Start by adding P[0] (which is 0) to the map with frequency 1.
- Initialize answer = 0.
- For k from 1 to n (inclusive) (since P has n+1 elements, indices 0..n):
For each f in FibSet:
target = P[k] - f
If target is in the frequency map, then add freq[target] to answer.
Then add P[k] to the frequency map (increment its count).
But wait: we are counting pairs (i, k) with i < k. When we are at k, we have in the map all prefix sums for indices i from 0 to k-1. So for each f, we look for P[i] = P[k] - f. That is correct.
However, note: we are iterating over all f in FibSet for each k. The size of FibSet is about O(log(max_diff)). So the total time is O(n * log(max_diff)). That should be acceptable if max_diff is up to 10^14 (log is about 50). But if the numbers are very large, max_diff could be huge? But note: the Fibonacci numbers we precompute are only up to max_diff. So the set size is about log_phi(max_diff). So it's small.
But what about memory? We store the frequency map of prefix sums. The number of distinct prefix sums could be up to n+1, but in worst case, they are all distinct? Possibly. So O(n) space.
However, there is a catch: what if the array has very large numbers and the prefix sums are huge? Then storing them in a map is fine, but the arithmetic might overflow? In Python, integers are arbitrary precision, so no problem.
But what about the condition that the subarray sum must be a Fibonacci number? We are only considering non-negative Fibonacci numbers. But what if the difference is negative? We are not considering that because we are only adding for f in FibSet (which are non-negative). But note: if P[k] < P[i], then P[k] - P[i] is negative, and we are not counting that because we are looking for P[i] = P[k] - f, and f>=0, so P[i] <= P[k]. So we are only counting pairs with P[i] <= P[k]. That is correct because we want non-negative difference.
But wait: what about f=0? Then we are counting pairs with P[i] = P[k]. That gives a subarray sum of 0, which is a Fibonacci number (if we include 0). So that's correct.
So the algorithm seems correct.
But is there any issue with the fact that we are counting each subarray exactly once? Yes, because for each subarray [i, j] we have k = j+1 and i. And we count it when we are at k and look for i.
However, note: we are iterating k from 1 to n. For k=0? We start with P[0] in the map, but then for k=1, we consider pairs (i=0, k=1). That corresponds to subarray [0,0] (since k=j+1, so j=k-1=0). So that's correct.
But what about the fact that we precomputed Fibonacci numbers up to max_diff? But note: the difference we are looking for is exactly f, and f is at most max_diff because we precomputed up to max_diff. But what if there is a pair (i,k) such that P[k]-P[i] is a Fibonacci number but larger than max_diff? That cannot happen because max_diff is the maximum possible difference. So we are safe.
However, note: we precomputed Fibonacci numbers up to max_diff, but what if the actual difference is less than or equal to max_diff? Then we have it. But what if max_diff is negative? That can't happen because max_diff = max(P) - min(P) >= 0. So it's non-negative.
But wait: what if the array is empty? Then n=0, then we have only P[0]=0. Then we are not counting any subarray because there are no subarrays? Actually, the problem says "array of integers", so maybe n>=1? But we should handle n=0: then answer is 0.
Let's test with a small example:
nums = [1,2,3]
P = [0,1,3,6]
minP=0, maxP=6, max_diff=6.
FibSet up to 6: {0,1,1,2,3,5}? Actually, Fibonacci: 0,1,1,2,3,5. So set: {0,1,2,3,5}.
Now, we have:
k=1: P[1]=1.
f in FibSet:
f=0 -> target=1 -> not in map (map has {0:1}) -> 0
f=1 -> target=0 -> found: freq[0]=1 -> ans+=1
f=2 -> target=-1 -> not found.
f=3 -> target=-2 -> not found.
f=5 -> target=-4 -> not found.
Then add P[1]=1 to map -> map: {0:1, 1:1}
k=2: P[2]=3.
f=0 -> target=3 -> not found.
f=1 -> target=2 -> not found.
f=2 -> target=1 -> found: freq[1]=1 -> ans+=1 (now ans=2)
f=3 -> target=0 -> found: freq[0]=1 -> ans+=1 (ans=3)
f=5 -> target=-2 -> not found.
Then add P[2]=3 -> map: {0:1,1:1,3:1}
k=3: P[3]=6.
f=0 -> target=6 -> not found.
f=1 -> target=5 -> not found.
f=2 -> target=4 -> not found.
f=3 -> target=3 -> found: freq[3]=1 -> ans+=1 (ans=4)
f=5 -> target=1 -> found: freq[1]=1 -> ans+=1 (ans=5)
Then add P[3]=6 -> map: {0:1,1:1,3:1,6:1}
So answer=5.
Let's list the subarrays:
[1]: sum=1 -> Fibonacci.
[2]: sum=2 -> Fibonacci.
[3]: sum=3 -> Fibonacci.
[1,2]: sum=3 -> Fibonacci.
[2,3]: sum=5 -> Fibonacci.
[1,2,3]: sum=6 -> not Fibonacci.
So we have 5. Correct.
Another example with negative numbers:
nums = [-1, 1]
P = [0, -1, 0]
minP=-1, maxP=0, max_diff=1.
FibSet up to 1: {0,1}.
k=1: P[1]=-1.
f=0 -> target=-1 -> not in map (map has {0:1})
f=1 -> target=-2 -> not found.
Then add -1 to map -> map: {0:1, -1:1}
k=2: P[2]=0.
f=0 -> target=0 -> found: freq[0]=1 -> ans+=1.
f=1 -> target=-1 -> found: freq[-1]=1 -> ans+=1.
Then add 0 -> map: {0:2, -1:1}
So answer=2.
Subarrays:
[-1]: sum=-1 -> not Fibonacci.
[1]: sum=1 -> Fibonacci.
[-1,1]: sum=0 -> Fibonacci.
So 2. Correct.
But wait: what about the subarray [0]? That would be a subarray of length 0? No, subarray must be contiguous and non-empty? The problem says "subarray", typically non-empty. But note: our method with prefix sums: for k=1 and i=0 gives subarray [0:0] which is the first element. That's non-empty. And for k=2 and i=0 gives [0:1] and i=1 gives [1:1]. So we are covering all non-empty contiguous subarrays.
However, note: what about the empty subarray? The problem says "subarray", and typically it means non-empty. But to be sure, let's check: if we consider empty subarray, its sum is 0, which is Fibonacci. But usually subarray problems do not include empty subarray unless stated. The problem says "subarray" without specification, but in the context of counting, it's usually non-empty. We can assume non-empty.
But in our method, we are only counting pairs with i < k, and k from 1 to n, so the subarray length is at least 1. So we are not counting empty subarray. Good.
However, what about the case when the array has a single element 0? Then:
nums=[0]
P=[0,0]
k=1: P[1]=0.
f=0 -> target=0 -> found: freq[0]=1 -> ans+=1.
f=1 -> target=-1 -> not found.
So answer=1. The subarray [0] has sum 0, which is Fibonacci. Correct.
So the algorithm seems correct.
But wait: what if there are duplicate Fibonacci numbers? For example, 1 appears twice in the Fibonacci sequence. But we are storing FibSet as a set, so we only consider each distinct value once. That is correct because we are looking for the sum to be a Fibonacci number, and if the sum is 1, it doesn't matter that 1 appears twice in the sequence.
However, note: in the Fibonacci sequence, 1 appears twice (F1 and F2). But we only need to check if the sum is 1, so set is fine.
Implementation details:
- Precompute Fibonacci numbers:
fibs = [0,1]
while fibs[-1] <= max_diff:
next = fibs[-1] + fibs[-2]
fibs.append(next)
Then FibSet = set(fibs) but note: we might have generated one beyond max_diff? We break when next > max_diff? Actually, we want all Fibonacci numbers <= max_diff. So we can do:
fibs = [0,1]
while True:
next = fibs[-1] + fibs[-2]
if next > max_diff:
break
fibs.append(next)
Then FibSet = set(fibs).
But note: what if max_diff is 0? Then we have fibs=[0,1]? But 1>0, so we break and then set is {0,1}? But we only need up to 0, so we should only include 0. So we must adjust: we should generate until the next Fibonacci exceeds max_diff, but then we have to include the last one that is <= max_diff. But in the loop, we are appending only if next <= max_diff. So if max_diff=0, then after [0,1], next=1 which is >0, so we break and we have [0,1]. But we don't want 1 because 1>0. So we should start with [0] and then generate? Actually, the Fibonacci sequence starts with 0,1. But if max_diff=0, we only need 0. So we can do:
fibs = [0]
a, b = 0, 1
while b <= max_diff:
fibs.append(b)
a, b = b, a+b
Then set(fibs).
But what about 1? If max_diff>=1, then we include 1. If max_diff=0, then we don't include 1.
Alternatively, we can generate all Fibonacci numbers up to max_diff by starting with 0 and 1, and then while the next is <= max_diff, append. But then if max_diff=0, we would have [0,1]? Because 1>0, so we break and we have [0,1] but then we take set? But 1 is not <= max_diff, so we shouldn't include it. So we must be careful.
Better:
fibs = [0,1]
while fibs[-1] <= max_diff:
next_val = fibs[-1] + fibs[-2]
if next_val > max_diff:
break
fibs.append(next_val)
Then remove any that are > max_diff? But we break when next_val>max_diff, so the last element in fibs might be <= max_diff? Actually, the condition in while is on the last element. But note: we start with [0,1]. If max_diff=0, then 1>0, so we don't enter the loop? Actually, the while condition is checked at the beginning of each iteration. So if max_diff=0, then fibs[-1]=1 which is >0, so we don't enter the loop. Then fibs is [0,1] but we only want 0. So we should not start with [0,1] unconditionally.
Instead, we can do:
fibs = [0]
a, b = 0, 1
while b <= max_diff:
fibs.append(b)
a, b = b, a+b
This way, if max_diff=0, we start with [0] and then b=1>0, so we don't append. So fibs=[0]. Good.
But what about the case when max_diff is 1? Then we append b=1 because 1<=1, then a=1, b=1+0? Wait, after first iteration: a=0, b=1 -> append 1, then a=1, b=0+1? That's wrong. The standard way:
a, b = 0, 1
while b <= max_diff:
fibs.append(b)
a, b = b, a+b
For max_diff=1:
Initially: a=0, b=1 -> 1<=1 -> append 1 -> fibs=[0,1]? But we started with [0]? Actually, we start with fibs=[0]. So after first iteration, we append b=1 -> fibs=[0,1]. Then a=1, b=0+1=1? That would be a=1, b=1? Then next: b=1<=1 -> append 1 again? That's wrong because we would get duplicate 1. So we must start with [0,1]? But then we would have two 1's? Actually, the Fibonacci sequence has two 1's? No, the sequence is 0,1,1,2,... so we have two 1's. But in a set, it doesn't matter. But if we are generating a list, we might get two 1's. But note: the condition while b<=max_diff: with a=1, b=1 -> then we append 1, then a=1, b=2 (since 1+1=2). Then 2>1? So we break. So we get [0,1,1]. That's fine because set will have {0,1}.
Alternatively, we can generate without duplicates by starting with [0,1] and then:
a, b = 0, 1
while True:
c = a + b
if c > max_diff:
break
fibs.append(c)
a, b = b, c
Then for max_diff=1: we start with fibs=[0,1], then c=0+1=1, which is <=1, so append 1 -> fibs=[0,1,1]. Then a=1, b=1, then c=1+1=2>1, break. So we have [0,1,1]. That's okay.
But note: we want all Fibonacci numbers up to max_diff. The Fibonacci sequence: F0=0, F1=1, F2=1, F3=2, ... So we need to include F0 and F1 and F2? Actually, if max_diff=1, then we need 0 and 1. But we have two 1's? It doesn't matter because set.
However, if we want to avoid duplicates, we can generate with:
fibs = [0,1]
a, b = 0, 1
while True:
c = a + b
if c > max_diff:
break
fibs.append(c)
a, b = b, c
Then for max_diff=0: we start with [0,1] but 1>0, so we break? Actually, we break after computing c? But we start with [0,1] already. So for max_diff=0, we have [0,1] but we only want 0. So we should not start with 1 if max_diff<1.
So better to generate dynamically:
fibs = [0]
a, b = 0, 1
while b <= max_diff:
fibs.append(b)
a, b = b, a+b
But as we saw, this produces two 1's if max_diff>=1? Let's test:
max_diff=1:
fibs=[0]
a=0, b=1 -> 1<=1 -> append 1 -> fibs=[0,1]; then a=1, b=0+1=1? Wait, after appending, we do a,b = b, a+b -> a=1, b=0+1=1? That's wrong because a was 0 and b was 1, then we set a=1, b=0+1=1? That gives b=1. Then next iteration: b=1<=1 -> append 1 -> fibs=[0,1,1]; then a=1, b=1+1=2 -> break. So we get two 1's.
To avoid duplicate 1, we can start with a=0, b=1 and then:
fibs = [0]
if max_diff >= 1:
fibs.append(1)
a, b = 1, 1
while True:
c = a + b
if c > max_diff:
break
fibs.append(c)
a, b = b, c
But that's messy.
Alternatively, we can just use a set and generate without worrying about duplicates:
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
This will generate:
a=0 -> add 0; then a=1, b=1.
a=1 -> add 1; then a=1, b=2.
a=1 -> add 1 (duplicate, set ignores); then a=2, b=3.
... until a > max_diff.
So for max_diff=0: we add 0, then a=1 which is >0, so we break? Actually, condition is while a<=max_diff. So after adding 0, we set a=1, then condition 1<=0 false, so we break. So set={0}. Good.
For max_diff=1:
add 0 -> set={0}
then a=1, b=1 -> condition 1<=1 true -> add 1 -> set={0,1}
then a=1, b=2 -> condition 1<=1 true -> add 1 (duplicate) -> set={0,1}
then a=2, b=3 -> condition 2<=1 false -> break.
So set={0,1}. Good.
So we can do:
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
Note: this generates Fibonacci numbers in order, and stops when the next Fibonacci number exceeds max_diff? Actually, we are adding a and then updating. So when a becomes the next Fibonacci number, we check if it is <= max_diff. But note: we are adding a before updating? Actually, we add the current a, then update to next. So we add F0, then F1, then F2? But in the second iteration, a becomes 1 (which is F1) and we add it. Then we update to a=1 (F2) and b=2. Then in the next iteration, a=1 (F2) which is <= max_diff? If max_diff=1, then we add 1 again? But set ignores duplicates. So it's fine.
But wait: the condition is while a <= max_diff. After we add a=1 (F1), we set a=1 (F2) and b=2. Then for max_diff=1, a=1<=1, so we add 1 again? But then we set a=2, b=3. Then a=2>1, break. So we added 1 twice. But set will have only one 1. So it's okay.
However, if we want to avoid duplicate iterations, we can do:
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
# Now a is the next Fibonacci number to be added in the next iteration.
But note: in the first iteration, we add 0, then set a=1, b=1.
Second iteration: a=1 <= max_diff -> add 1, then set a=1, b=2.
Third iteration: a=1 <= max_diff -> add 1 again? That's because we have two consecutive 1's in the Fibonacci sequence. But we want to include both? Actually, the Fibonacci sequence has two 1's, but they are the same number. So set doesn't care.
So this is acceptable.
But note: what if max_diff is very large? The while loop runs about O(log(max_diff)) times, which is fine.
Now, the main loop:
freq = defaultdict(int)
freq[0] = 1 # P[0] = 0
ans = 0
for k in range(1, n+1):
for f in fib_set:
target = P[k] - f
if target in freq:
ans += freq[target]
freq[P[k]] += 1
But note: we are iterating over fib_set for each k. The size of fib_set is about O(log(max_diff)). So total time O(n * log(max_diff)).
However, what if max_diff is huge? But note that max_diff is the range of prefix sums. If the numbers are huge, then max_diff could be huge, but the number of Fibonacci numbers up to max_diff is still logarithmic in max_diff. So even if max_diff is 10^18, log_phi(10^18) is about 90. So it's fine.
But what if the array length is very large, say 10^6? Then 10^6 * 90 = 90e6, which is acceptable in Python? Maybe in PyPy or C++ but in Python it might be borderline. But note: the inner loop is over a set of about 90 elements, so it's 90 * n. For n=10^6, that's 90e6 iterations, which in Python might take a few seconds. But we can try to optimize by not iterating over all f if we can? Alternatively, we can change the order: for each prefix sum we have seen, we can check if there exists a Fibonacci number f such that P[k] - P[i] = f. But that would require for each i, checking if (P[k] - P[i]) is in fib_set. But then we would have to iterate over all i, which is O(n) for each k, leading to O(n^2). So the current method is better.
But note: we are iterating over fib_set for each k. That is O(|fib_set|) per k. So total O(n * |fib_set|). And |fib_set| is about log(max_diff). So if max_diff is 10^18, |fib_set|~90. So for n=10^6, 90e6 is acceptable in C++ but in Python might be slow. However, we can try to reduce the constant factor by using a list for fib_set and then iterating, but set iteration is fast.
Alternatively, we can precompute the list of Fibonacci numbers and then for each k, we can compute the required targets and check in the map. That's what we are doing.
But what if the array has negative numbers? Then P[k] can be negative. Then target = P[k] - f, with f>=0, so target <= P[k]. So if P[k] is negative, then target is negative and we might have negative keys in the map. That's fine.
However, we must be cautious about integer overflow? In Python, no.
One more issue: what if the array is huge and the prefix sums are huge, but the Fibonacci numbers are only up to max_diff. But what if the difference between two prefix sums is a Fibonacci number that is larger than max_diff? That cannot happen because max_diff is the maximum difference. So we are safe.
But wait: what if the array has both positive and negative numbers and the maximum difference is not max(P)-min(P)? For example, if we have P = [0, 10, 5, 15]. Then max(P)=15, min(P)=0, max_diff=15. But what about the pair (i=1, k=3): P[3]=15, P[1]=10, difference=5 which is <=15. And (i=2, k=3): difference=10, which is <=15. So all differences are <= max_diff. So it's correct.
However, note that we are only considering pairs with i<k and we are looking at P[k]-P[i]. The maximum of P[k]-P[i] over all i<k is at most max(P) - min(P). So we are covering all.
But wait: what if the array is [100, -100, 100]? Then P = [0,100,0,100]. The maximum difference is 100 (from P[1]=100 and P[2]=0, or P[3]=100 and P[2]=0). So max_diff=100. But note: the subarray from index 0 to 2: [100,-100,100] has sum 100, which is Fibonacci. And we would count it when k=3 and i=0: P[3]-P[0]=100. That is covered. Also, the subarray [100] at index0: sum=100, counted when k=1 and i=0. So it's fine.
So the algorithm is:
Def count_fib_subarrays(nums):
n = len(nums)
P = [0]*(n+1)
for i in range(n):
P[i+1] = P[i] + nums[i]
minP = min(P)
maxP = max(P)
max_diff = maxP - minP
# Generate Fibonacci set up to max_diff.
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
# Now count
from collections import defaultdict
freq = defaultdict(int)
freq[0] = 1 # P[0]
ans = 0
for k in range(1, n+1):
for f in fib_set:
target = P[k] - f
if target in freq:
ans += freq[target]
freq[P[k]] += 1
return ans
But wait: what about the fact that we are using a set for fib_set. The set iteration order doesn't matter.
However, note: if max_diff is 0, then fib_set = {0}. Then for each k, we look for target = P[k] - 0 = P[k]. So we are counting the number of i with P[i] = P[k]. That counts subarrays with sum 0. But note: if there are multiple occurrences of the same prefix sum, we count each pair.
Example: nums = [0,0]. Then P=[0,0,0].
k=1: P[1]=0, fib_set={0}, target=0, freq[0]=1 -> ans+=1. Then freq[0] becomes 2.
k=2: P[2]=0, target=0, freq[0]=2 -> ans+=2. Then freq[0] becomes 3.
So ans=3.
Subarrays: [0] at index0, [0] at index1, [0,0] -> all have sum 0. So 3. Correct.
So it works.
But what about performance? If the array is very long, say n=10^6, and the numbers are such that the prefix sums are all distinct? Then the frequency map will have n+1 entries. And for each k, we iterate over about 90 Fibonacci numbers. So 90 * 10^6 = 90e6, which in Python might take a few seconds. But if the numbers are huge, then the Fibonacci set might be larger? Actually, the number of Fibonacci numbers up to max_diff is about 4.78 * log10(max_diff) (since phi≈1.618, so log_phi(max_diff) ≈ log(max_diff)/log(phi) ≈ 2.078 * log10(max_diff)). For max_diff=10^18, log10=18, so about 37. So it's around 40. So 40 * 10^6 = 40e6, which is acceptable.
But what if max_diff is 10^100? Then the number of Fibonacci numbers up to 10^100 is about 100*2.078 ≈ 208. So still linear in the number of digits. So for n=10^6, 200e6 iterations might be borderline in Python but maybe acceptable in PyPy or with pypy. But note: the inner loop is very simple: just a subtraction and a dictionary lookup. So it might be okay.
However, we can try to optimize by not iterating over all Fibonacci numbers for each k? We can note that for a given P[k], the targets we are looking for are P[k] - f for f in fib_set. But if we have the frequency map of prefix sums, we could for each prefix sum value that we have seen, check if (P[k] - that value) is in fib_set. But then we would have to iterate over all distinct prefix sums? That could be up to n, and then for each we do a set lookup, so O(n) per k, which is O(n^2). That's worse.
Alternatively, we can precompute for each possible difference? But that's not possible.
Another idea: since the Fibonacci set is small, we can for each f in fib_set, maintain a separate frequency map for (P[i] - f)? But that would be complicated.
So the current method seems best.
But wait: what if the array has very large numbers and the prefix sums are huge, but the Fibonacci set is small. Then we are doing O(n * |fib_set|) operations, which is O(n log(max_diff)). That's acceptable.
However, note that the problem might have constraints that n is up to 10^5 and numbers up to 10^9. Then max_diff could be 10^14, |fib_set|~70, so 7e6 operations, which is fine.
Let's code accordingly.
But one more thing: we are using a set for fib_set. The set lookup is O(1) average. So the inner loop: for each f, compute target and check in freq (which is a dict). So that's O(1) per f.
So overall O(n * |fib_set|).
Edge case: if max_diff is 0, then fib_set = {0}. Then we are only counting pairs with P[i] = P[k]. That is correct.
But what if the array has no subarray with sum being a Fibonacci number? Then answer 0.
Let's test with nums=[4]. Then P=[0,4]. max_diff=4. fib_set: {0,1,1,2,3}? Actually, Fibonacci up to 4: 0,1,1,2,3. So set={0,1,2,3}.
k=1: P[1]=4.
f=0 -> target=4 -> not in freq (freq has {0:1})
f=1 -> target=3 -> not found.
f=2 -> target=2 -> not found.
f=3 -> target=1 -> not found.
So ans=0. Correct because 4 is not Fibonacci.
What about nums=[1]? Then P=[0,1]. fib_set={0,1}.
k=1: f=0 -> target=1 -> not found? Actually, freq has {0:1}. So for f=0: target=1 -> not in freq. For f=1: target=0 -> found: freq[0]=1 -> ans=1. So correct.
What about nums=[0]? Then P=[0,0]. fib_set={0}.
k=1: f=0 -> target=0 -> found: freq[0]=1 -> ans=1. Correct.
What about nums=[2]? Then P=[0,2]. fib_set up to 2: {0,1,2}.
k=1: f=0 -> target=2 -> not found.
f=1 -> target=1 -> not found.
f=2 -> target=0 -> found: ans=1. So correct because 2 is Fibonacci.
So it seems correct.
But wait: what about the Fibonacci number 1? In the example with nums=[1], we got ans=1. But note: the subarray [1] has sum 1, which is Fibonacci. And we also have the subarray? Only one subarray.
What about nums=[1,1]?
P=[0,1,2]
fib_set up to 2: {0,1,2}
k=1: P[1]=1.
f=0 -> target=1 -> not found (freq: {0:1})
f=1 -> target=0 -> found: ans+=1.
f=2 -> target=-1 -> not found.
then freq[1]=1.
k=2: P[2]=2.
f=0 -> target=2 -> not found.
f=1 -> target=1 -> found: freq[1]=1 -> ans+=1 (total 2)
f=2 -> target=0 -> found: freq[0]=1 -> ans+=1 (total 3)
then freq[2]=1.
So ans=3.
Subarrays: [1] (first), [1] (second), [1,1] (sum=2). All Fibonacci? 1,1,2 are Fibonacci. So 3. Correct.
What about nums=[1,3]?
P=[0,1,4]
max_diff=4, fib_set={0,1,2,3}
k=1: P[1]=1.
f=0 -> target=1 -> not found.
f=1 -> target=0 -> found: ans=1.
f=2 -> target=-1 -> not.
f=3 -> target=-2 -> not.
freq[1]=1.
k=2: P[2]=4.
f=0 -> target=4 -> not.
f=1 -> target=3 -> not.
f=2 -> target=2 -> not.
f=3 -> target=1 -> found: freq[1]=1 -> ans=2.
So answer=2.
Subarrays: [1] (sum=1), [1,3] (sum=4 not Fibonacci), [3] (sum=3). So [1] and [3] are Fibonacci. So 2. Correct.
So the algorithm seems solid.
However, note: we are counting subarrays that have sum exactly a Fibonacci number. But what if the sum is a large Fibonacci number that we didn't generate because max_diff is not large enough? But we generated up to max_diff, so if the sum is at most max_diff, we have it. And if the sum is greater than max_diff, then it cannot be a Fibonacci number because we generated all Fibonacci numbers up to max_diff and the next Fibonacci number is greater than max_diff. But wait: what if the sum is a Fibonacci number that is greater than max_diff? That would mean that there exists a pair (i,k) such that P[k]-P[i] > max_diff. But max_diff is defined as max(P)-min(P), so for any i and k, P[k]-P[i] <= max(P)-min(P) = max_diff. So it cannot be greater. Therefore, we are safe.
Therefore, we have an O(n * log(max_diff)) time algorithm and O(n) space.
But note: the generation of fib_set is O(log(max_diff)), which is negligible.
Let's write the code accordingly.
However, one more thought: what if the array is very long and the numbers are very large, but the prefix sums are not too spread? Then max_diff might be small. But worst-case, the prefix sums could be spread out.
We'll implement as described.
But wait: what about negative Fibonacci numbers? The problem says "Fibonacci number", which typically means non-negative. So we assume non-negative.
So final function:
from collections import defaultdict
def count_fib_subarrays(nums):
n = len(nums)
if n == 0:
return 0
# Compute prefix sums
P = [0]*(n+1)
for i in range(n):
P[i+1] = P[i] + nums[i]
minP = min(P)
maxP = max(P)
max_diff = maxP - minP
# Generate Fibonacci numbers up to max_diff (non-negative)
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
# Count subarrays
freq = defaultdict(int)
freq[0] = 1 # P[0]
ans = 0
for k in range(1, n+1):
for f in fib_set:
target = P[k] - f
if target in freq:
ans += freq[target]
freq[P[k]] += 1
return ans
Let's test with the examples we did.
But wait: what if the array has a subarray sum that is a Fibonacci number but we didn't generate that Fibonacci number because max_diff is computed from the prefix sums? But we generated up to max_diff, and the subarray sum is at most max_diff. So it's fine.
However, note: the subarray sum is P[k]-P[i]. And we have that P[k] and P[i] are in the array P. So the difference is at most maxP-minP = max_diff. So we are generating all Fibonacci numbers up to that.
But what if the array has negative numbers and the minimum prefix sum is negative? Then max_diff = maxP - minP could be larger than maxP? For example, if minP is negative, then maxP - minP > maxP. But the subarray sum P[k]-P[i] could be as large as maxP - minP, which is larger than maxP. But we generate Fibonacci numbers up to that. So it's fine.
Example: nums = [-5, 10]. Then P=[0,-5,5]. minP=-5, maxP=5, max_diff=10. fib_set up to 10: includes 0,1,1,2,3,5,8. The subarray [-5,10] has sum 5, which is in the set. And the subarray [10] has sum 10, which is also in the set? 10 is not a Fibonacci number. So we don't count it. But note: the subarray [-5] has sum -5, which is not Fibonacci. So only one subarray? Actually, [10] sum=10 not Fibonacci. So only one.
Our algorithm:
k=1: P[1]=-5.
for f in fib_set (0,1,2,3,5,8):
target = -5 - f. None of these are in freq (freq has {0:1}).
then freq[-5]=1.
k=2: P[2]=5.
f=0 -> target=5 -> not in freq (freq: {0:1, -5:1})
f=1 -> target=4 -> not
f=2 -> target=3 -> not
f=3 -> target=2 -> not
f=5 -> target=0 -> found: freq[0]=1 -> ans+=1.
f=8 -> target=-3 -> not.
Then freq[5]=1.
So ans=1. Correct.
But wait: what about the subarray from index0 to index1? That's [-5,10] which we counted when k=2 and i=0? Actually, we have P[2]=5, P[0]=0, so f=5. We did count that. So correct.
So it works.
However, note that we are using a set for fib_set. The set iteration might be in arbitrary order, but that doesn't matter.
But what if max_diff is very large and we generate a lot of Fibonacci numbers? The number of Fibonacci numbers up to M is about log_phi(M). For M=10^18, it's about 90. For M=10^100, it's about 500. So even for M=10^100, 500 * n (with n=10^6) is 5e8, which might be too slow in Python. But note: if the numbers are such that the prefix sums are huge, then n is probably not that large? The problem doesn't specify constraints. We must assume that n is up to 10^5 or 10^6 and the numbers are up to 10^9, so max_diff up to 10^14, which gives about 70 Fibonacci numbers. So 70 * 10^6 = 7e6, which is fine.
But if the numbers are arbitrary precision and the array is long, then we might have to worry about the size of the Fibonacci set. However, note that the Fibonacci numbers grow exponentially, so even if the numbers are huge, the number of Fibonacci numbers up to that is still logarithmic in the value. So if the numbers are 100 digits long, then max_diff could be 200 digits, and the number of Fibonacci numbers up to 10^200 is about 200 * 2.078 ≈ 415. So 415 * n. For n=10^5, that's 41.5e6, which is acceptable.
So we'll go with this.
However, there is one more optimization: we can break early in the inner loop if f > P[k] - minP? But note: we are looking for target = P[k] - f. If f is very large, then target becomes very small. But we are checking if target is in freq. Since freq only contains prefix sums that we have seen, and the minimum prefix sum is minP, then if target < minP, then it's not in freq. But we don't know minP at the time of the loop? We have minP computed. So we can do: if P[k] - f < minP, then we can break? But note: fib_set is not sorted? We can sort fib_set and then break when f > P[k] - minP? But wait: we are iterating over fib_set, which is a set. We can convert to a sorted list and then iterate. But then we can break when f > P[k] - minP because then target = P[k]-f < minP, and since minP is the minimum prefix sum we have seen (and we have seen all prefix sums from 0 to k-1, but note: the minimum of all prefix sums is minP, but the prefix sums we have seen so far (i<k) might have a minimum that is at least minP? Actually, the minimum of all prefix sums is minP, but the prefix sums we have seen so far (indices 0..k-1) might be greater than minP? For example, if minP occurs at an index >= k? Then when we are at k, we haven't seen that minimum yet. So the minimum of the prefix sums we have seen so far might be greater than the overall minP. So we cannot use the overall minP to break.
Alternatively, we can maintain the current minimum of the prefix sums we have seen? But that would require updating as we go, and then for each k, we can break when f > P[k] - current_min. But current_min is the minimum of P[0..k-1]. That is easy to maintain. Then if f > P[k] - current_min, then target < current_min, and since all seen prefix sums are >= current_min, target cannot be in freq. So we can break the inner loop when f > P[k] - current_min. But note: fib_set is not sorted. So we should sort fib_set and then iterate in increasing order? Then we can break when f exceeds the threshold.
But wait: we are iterating over all f in fib_set. If we sort fib_set, then we can break early when f > P[k] - current_min. But note: we are looking for target = P[k] - f. For a fixed k, as f increases, target decreases. So if we iterate f in increasing order, then when f becomes too large such that target < current_min, then we can break because for larger f, target will be even smaller. So we can break.
But is it worth it? The set fib_set is small (about 100 elements). So sorting it once and then iterating in sorted order for each k might not save much. But we can try.
Alternatively, we can for each k, compute the maximum f that we need to consider: f_max = P[k] - current_min. Then we only consider f in fib_set that are <= f_max. But then we have to iterate over all f in fib_set and check if f <= f_max. That's the same as breaking early if we iterate in sorted order.
Since fib_set is small, we can just convert it to a sorted list once and then for each k, iterate until f > P[k] - current_min.
But we need to maintain current_min. We can do:
current_min = 0 # at the beginning, we have seen P[0]=0.
for k in range(1, n+1):
# update current_min? Actually, we are about to add P[k] after processing. But during processing, we have seen P[0..k-1]. So the current minimum is min(P[0..k-1]). We can maintain that as we go.
# But we have the overall minP? We can use min(P[0..k-1]) which we can compute by keeping a running minimum.
Actually, we can do:
min_so_far = 0 # because P[0]=0
for k in range(1, n+1):
# min_so_far is the minimum of P[0..k-1]
# Now for each f in sorted_fib:
# if f > P[k] - min_so_far: break
# else: check target = P[k]-f in freq.
# Then update min_so_far = min(min_so_far, P[k])
But note: we are adding P[k] after the inner loop. So during the inner loop, we haven't added P[k] to freq. So the seen prefix sums are exactly P[0..k-1]. So the minimum of seen prefix sums is min_so_far.
We can initialize min_so_far = 0.
Then for k=1: min_so_far = 0.
After processing k=1, we update min_so_far = min(min_so_far, P[1]).
Then for k=2: min_so_far is min(0, P[1]).
So we can do:
sorted_fib = sorted(fib_set)
min_so_far = 0
ans = 0
freq = defaultdict(int)
freq[0] = 1
for k in range(1, n+1):
# For each f in sorted_fib, but break when f > P[k] - min_so_far
for f in sorted_fib:
if f > P[k] - min_so_far:
break
target = P[k] - f
if target in freq:
ans += freq[target]
# update min_so_far and freq
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] += 1
But wait: what if P[k] - min_so_far is negative? Then f (which is non-negative) will always be > negative? So the condition f > P[k] - min_so_far will be true for the smallest f (which is 0) if P[k] - min_so_far is negative? Actually, if P[k] - min_so_far is negative, then since f>=0, we have f > negative always true. So we break immediately and skip all f. That is correct because if P[k] - min_so_far < 0, then for all f>=0, target = P[k]-f <= P[k] < min_so_far, so target cannot be in the seen prefix sums (which are all >= min_so_far). So we break.
But note: if P[k] - min_so_far is negative, then we break and skip all f. That's correct.
However, what if P[k] - min_so_far is 0? Then we only consider f=0? Because f>0 would be >0? So we break after f=0? But we need to check f=0. So condition: if f > P[k]-min_so_far: break. So when f=0, 0 > 0? False, so we check. Then for f=1, 1>0 -> true, so break. So we only check f=0. That's correct because if P[k] - min_so_far = 0, then only f=0 gives target = P[k] which might be in the map? But wait: we are looking for target = P[k] - f. For f=0, target=P[k]. But if P[k] is in the map? We haven't added P[k] yet. But we are looking for i<k, so P[i] must be in the map from indices <k. And min_so_far is the minimum of P[0..k-1]. If P[k] - min_so_far = 0, then P[k] = min_so_far. So target = min_so_far. And since min_so_far is the minimum of the seen prefix sums, it must be in the map? Not necessarily: the minimum value might appear multiple times, but at least one occurrence? Since min_so_far is the minimum of P[0..k-1], there exists at least one i in [0,k-1] with P[i] = min_so_far. So if f=0, then target = P[k] = min_so_far, which is in the map. So we should count it. But wait: we break when f > P[k]-min_so_far. For f=0, we don't break. For f=1, we break because 1>0. So we only check f=0. That's correct because for any f>0, target = P[k]-f < P[k] = min_so_far, so cannot be in the map. So we break.
So this optimization works.
But note: we are using sorted_fib. We need to sort fib_set once. That's O(|fib_set| log |fib_set|) which is negligible.
However, what if the array has negative prefix sums and P[k] is negative? Then P[k] - min_so_far could be positive? For example, if min_so_far is -10 and P[k] = -5, then P[k]-min_so_far = 5. Then we consider f up to 5. That's correct.
So we can implement this optimization to reduce the inner loop iterations.
But is it necessary? For each k, we are iterating over all f in fib_set. With the optimization, we break when f > P[k] - min_so_far. So the number of f we consider is at most the number of Fibonacci numbers <= (P[k] - min_so_far). Since fib_set is sorted, we can break early.
Without optimization, we always iterate over all f. With optimization, we might break early. But in worst case, we still might have to iterate over all f if P[k] - min_so_far is large. But note that P[k] - min_so_far is at most max_diff? Actually, min_so_far is the minimum of P[0..k-1], so P[k] - min_so_far <= maxP - minP = max_diff. And fib_set contains Fibonacci numbers up to max_diff. So in the worst case, we iterate over all f. But on average, it might be less.
But the set is small, so it's not a big deal.
We'll implement without this optimization first, and then if needed we can add.
However, note that the inner loop is over a set. If we convert to a sorted list, then we can break early. But if we keep it as a set, we cannot break early because set iteration is arbitrary. So we must convert to a sorted list to break early.
Let's do:
sorted_fib = sorted(fib_set)
Then in the loop:
for f in sorted_fib:
if f > P[k] - min_so_far:
break
target = P[k] - f
if target in freq:
ans += freq[target]
But wait: what if P[k] - min_so_far is negative? Then for f=0, 0 > negative? No, 0 is not greater than negative. So we would check f=0? But then for f=0, target = P[k] which is less than min_so_far? Actually, if P[k] - min_so_far is negative, then P[k] < min_so_far. So target = P[k] - f <= P[k] < min_so_far. So for f=0, target = P[k] < min_so_far, so it cannot be in freq. But we are still checking it. We could break immediately if P[k] < min_so_far? But note: min_so_far is the minimum of P[0..k-1]. If P[k] < min_so_far, then P[k] is even smaller. But then for any f>=0, target = P[k]-f <= P[k] < min_so_far, so none of them can be in the map. So we can break the entire inner loop if P[k] < min_so_far? Actually, if P[k] < min_so_far, then P[k] is the new minimum? But we haven't updated min_so_far yet. But note: the condition for a valid target is that target must be at least min_so_far (since all seen prefix sums are >= min_so_far). So if P[k] < min_so_far, then for any f>=0, target = P[k]-f <= P[k] < min_so_far, so no target can be in the map. So we can skip the inner loop entirely.
So we can do:
if P[k] < min_so_far:
# then no f will give a target in the seen prefix sums, because target <= P[k] < min_so_far.
# so skip inner loop.
else:
for f in sorted_fib:
if f > P[k] - min_so_far:
break
target = P[k] - f
if target in freq:
ans += freq[target]
But wait: what about f=0? Then target = P[k]. If P[k] is in the map? But we haven't added P[k] yet. And P[k] might be equal to some previous prefix sum. But if P[k] < min_so_far, then P[k] is less than the minimum of the seen prefix sums, so it cannot be equal to any seen prefix sum. So indeed, no f will work.
So we can skip the inner loop if P[k] < min_so_far.
Also, if P[k] >= min_so_far, then we consider f from 0 up to at most P[k] - min_so_far.
But note: what if P[k] == min_so_far? Then we only consider f=0? Because for f>0, target = P[k]-f < min_so_far. So we break after f=0.
So we can do:
if P[k] >= min_so_far:
for f in sorted_fib:
if f > P[k] - min_so_far:
break
target = P[k] - f
if target in freq:
ans += freq[target]
And if P[k] < min_so_far, we skip.
But wait: what about the case when P[k] is negative and min_so_far is negative? Then P[k] might be greater than min_so_far? For example, min_so_far = -10, P[k] = -5. Then P[k] - min_so_far = 5. So we consider f up to 5.
So the condition is P[k] >= min_so_far? Actually, if P[k] is negative and min_so_far is more negative, then P[k] > min_so_far. So we do the inner loop.
So the condition to skip is when P[k] < min_so_far? That is when P[k] is less than the current minimum. But then the difference P[k] - min_so_far is negative? Actually, if P[k] < min_so_far, then P[k] - min_so_far < 0. So we skip.
Alternatively, we can compute threshold = P[k] - min_so_far. If threshold < 0, then skip. But threshold = P[k] - min_so_far. If P[k] < min_so_far, then threshold < 0. So we can do:
threshold = P[k] - min_so_far
if threshold < 0:
# skip
else:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
But note: threshold = P[k] - min_so_far. And we are breaking when f > threshold. That is equivalent to f > P[k] - min_so_far.
So we can do:
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
This is the same as before.
But wait: what if min_so_far is not the overall minimum? But we are using the minimum of the seen prefix sums. That's correct because we only care about seen prefix sums.
So we can maintain min_so_far.
However, note: we update min_so_far after processing k? Actually, during the inner loop, we are considering seen prefix sums which are P[0..k-1]. So min_so_far should be the minimum of P[0..k-1]. We update it after the inner loop by min_so_far = min(min_so_far, P[k]). But wait: we are using min_so_far in the inner loop. So at the start of the loop for k, min_so_far is the minimum of P[0..k-1]. That's correct.
So we can do:
sorted_fib = sorted(fib_set)
min_so_far = 0
freq = defaultdict(int)
freq[0] = 1
ans = 0
for k in range(1, n+1):
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
# update min_so_far and freq
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] += 1
But wait: what about the case when threshold is exactly a Fibonacci number? We are including f that are <= threshold. So if threshold is a Fibonacci number, we include it. That's correct.
However, note: the condition f > threshold: when f equals threshold, we don't break. We break only when f exceeds threshold. So we include f=threshold.
Example: if threshold=5, and fib_set has 5, then we include f=5.
So this is correct.
But what about the case when P[k] - min_so_far is negative? Then we skip the inner loop. That's correct because then for any f>=0, target = P[k]-f < min_so_far, so not in the map.
But wait: what if min_so_far is negative and P[k] is negative but P[k] > min_so_far? Then threshold is positive. So we do the inner loop. That's correct.
So we can implement this optimization.
However, note that we are using sorted_fib. We generate fib_set and then sort it once.
But is the optimization worth it? It might reduce the inner loop iterations. For example, if P[k] is very small compared to min_so_far? Actually, if P[k] is less than min_so_far, we skip. If P[k] is just a little above min_so_far, then threshold is small, so we break early. But if P[k] is large, then threshold is large and we iterate over all f. So worst-case, we still iterate over all f.
But in practice, it might help.
However, note that the set fib_set is small. So we might not need it.
We'll implement without optimization first, and then if performance is an issue, we can add.
But let's consider the worst-case: all prefix sums are increasing? Then min_so_far = 0 (since P[0]=0 and all P[k] >0). Then threshold = P[k] - 0 = P[k]. And P[k] can be large. So we iterate over all f. That's the worst-case.
If the prefix sums are decreasing, then min_so_far becomes more negative, and P[k] might be negative. Then threshold = P[k] - min_so_far. Since min_so_far is the minimum so far, and P[k] might be greater than min_so_far, then threshold is positive. But if P[k] is negative and min_so_far is very negative, then threshold could be large positive? Example: min_so_far = -100, P[k] = -50, then threshold = 50. So we iterate over all f up to 50. That might be many if fib_set has many numbers up to 50? But the number of Fibonacci numbers up to 50 is about 10? Actually, Fibonacci: 0,1,1,2,3,5,8,13,21,34,55. So up to 50: 0,1,1,2,3,5,8,13,21,34. That's 10 numbers. So it's still small.
So even without optimization, the inner loop is over about 10-100 numbers. So it's fine.
We'll stick to the simple version without the optimization for clarity.
But note: the simple version does not break early and iterates over all f in fib_set for each k. That's acceptable.
Let's code accordingly.
However, one more thing: what if the array is huge and the prefix sums are huge, and the Fibonacci set is large? For example, if max_diff is 10^100, then fib_set has about 500 numbers. Then for n=10^6, that's 500e6 iterations, which in Python might be slow. But 500e6 iterations in Python might take several seconds. We can try to optimize by using the threshold break.
We'll implement with the threshold break and sorted fib_set.
Steps:
fib_set = generate as above.
sorted_fib = sorted(fib_set) # ascending order
min_so_far = 0
freq = defaultdict(int)
freq[0] = 1
ans = 0
for k in range(1, n+1):
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
# update min_so_far and freq
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] += 1
This way, we break early in the inner loop when f exceeds threshold.
But wait: what if threshold is 0? Then we only consider f=0? Because for f=0, 0>0 is false, so we check f=0. Then for f=1, 1>0 true, break. So we only check f=0. That's correct.
What if threshold is 1? Then we check f=0 and f=1? Because sorted_fib might be [0,1,1,2,...]. We have two 1's? But set doesn't have duplicates. So sorted_fib will have [0,1,2,...]. So we check f=0 and f=1. Then for f=2, 2>1 break. So we check f=0 and f=1. That's correct.
But note: there are two 1's in the Fibonacci sequence, but set has only one 1. So we are not counting twice for the same Fibonacci number. That's correct because we only care if the sum is a Fibonacci number, not how many times it appears in the sequence.
So this is fine.
However, what about the case when threshold is very large? Then we iterate over all f in sorted_fib until we reach one that exceeds threshold. Since sorted_fib is sorted, we break when f > threshold. But if threshold is larger than the last Fibonacci number in fib_set, then we iterate over all. That's the worst-case.
But note: the last Fibonacci number in fib_set is at most max_diff. And threshold = P[k] - min_so_far. Since min_so_far is the minimum of P[0..k-1], we have min_so_far >= overall minP. So threshold <= P[k] - minP. But P[k] <= maxP, so threshold <= maxP - minP = max_diff. So threshold is at most max_diff. And fib_set contains Fibonacci numbers up to max_diff. So the last element of sorted_fib is at most max_diff. Therefore, if threshold is exactly max_diff, then we will iterate over all f because the last f is <= threshold. But if threshold is less than the last f, we break earlier.
So the worst-case is when threshold is at least the last Fibonacci number, then we iterate over all. But that's the same as without optimization.
But on average, threshold might be smaller.
We'll implement with the optimization.
But wait: we are using min_so_far which is the minimum of P[0..k-1]. But note: when we are at k, we have not added P[k] to freq yet. So the seen prefix sums are exactly P[0..k-1]. So min_so_far is correct.
However, we update min_so_far after the inner loop. That's correct because during the inner loop, we are considering seen prefix sums (indices 0..k-1), so min_so_far should be the minimum of those.
So the algorithm is:
compute P[0..n]
compute minP, maxP, max_diff
generate fib_set up to max_diff
sorted_fib = sorted(fib_set)
min_so_far = 0
freq = {0:1}
ans = 0
for k in range(1, n+1):
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] = freq.get(P[k], 0) + 1
return ans
Let's test with a small example where threshold is not the full size.
nums = [1,2,3] as before.
P=[0,1,3,6]
sorted_fib = [0,1,2,3,5] (since max_diff=6, we have up to 5? Actually, Fibonacci up to 6: 0,1,1,2,3,5. So set: {0,1,2,3,5}. Sorted: [0,1,2,3,5].
min_so_far = 0
k=1: P[1]=1, threshold=1-0=1 >=0.
f=0: 0<=1 -> target=1 -> not in freq (freq{0:1})
f=1: 1<=1 -> target=0 -> in freq -> ans+=1.
f=2: 2>1 -> break.
Then update min_so_far: min(0,1)=0.
freq[1]=1.
k=2: P[2]=3, threshold=3-0=3.
f=0: target=3 -> not in freq.
f=1: target=2 -> not.
f=2: target=1 -> in freq (freq: {0:1,1:1}) -> ans+=1 (total 2)
f=3: target=0 -> in freq -> ans+=1 (total 3)
f=5: 5>3 -> break.
Then update min_so_far: min(0,3)=0.
freq[3]=1.
k=3: P[3]=6, threshold=6-0=6.
f=0: target=6 -> not in freq.
f=1: target=5 -> not.
f=2: target=4 -> not.
f=3: target=3 -> in freq -> ans+=1 (total 4)
f=5: target=1 -> in freq -> ans+=1 (total 5)
Then break because next f? There is no next.
update min_so_far: min(0,6)=0.
freq[6]=1.
So ans=5. Correct.
But wait: in the example above, for k=3, we had f=3 and f=5. That's correct.
Now, what if we didn't break early? We would have checked f=0,1,2,3,5. That's the same. So in this case, we didn't break early because threshold was 6 and the last f is 5, so we didn't break until after f=5. So no saving.
But what if threshold is smaller? For example, if the array is [1,1,1]?
P=[0,1,2,3]
max_diff=3, fib_set={0,1,2,3}? Actually, Fibonacci up to 3: 0,1,1,2,3. So set: {0,1,2,3}. sorted_fib=[0,1,2,3].
min_so_far=0
k=1: P[1]=1, threshold=1.
f=0: target=1 -> not in freq (freq{0:1})
f=1: target=0 -> in freq -> ans=1.
f=2: 2>1 -> break.
k=2: P[2]=2, threshold=2.
f=0: target=2 -> not.
f=1: target=1 -> in freq (freq: {0:1,1:1}) -> ans=2.
f=2: target=0 -> in freq -> ans=3.
f=3: 3>2 -> break.
k=3: P[3]=3, threshold=3.
f=0: target=3 -> not.
f=1: target=2 -> in freq (freq: {0:1,1:1,2:1}) -> ans=4.
f=2: target=1 -> in freq -> ans=5.
f=3: target=0 -> in freq -> ans=6.
So ans=6.
Subarrays: [1], [1], [1], [1,1], [1,1], [1,1,1]? Wait, let's list:
[1] at index0: sum=1 -> Fibonacci.
[1] at index1: sum=1 -> Fibonacci.
[1] at index2: sum=1 -> Fibonacci.
[1,1] at [0,1]: sum=2 -> Fibonacci.
[1,1] at [1,2]: sum=2 -> Fibonacci.
[1,1,1]: sum=3 -> Fibonacci.
So 6. Correct.
With the break, for k=1 we broke after f=1. For k=2 we broke after f=2? Actually, after f=2 we break because next f=3>2. So we didn't check f=3 for k=2. But we didn't need to because f=3 would give target=-1, which is not in the map. So it's fine.
For k=3, we didn't break until after f=3 because threshold=3 and f=3 is included. So we checked all.
So the break is working.
Now, what about the case when threshold is negative? Example: nums = [-1, -2]. Then P=[0,-1,-3].
min_so_far=0
k=1: P[1]=-1, threshold = -1 - 0 = -1 -> negative, so skip inner loop.
Then update min_so_far = min(0, -1) = -1.
freq[-1]=1.
k=2: P[2]=-3, threshold = -3 - (-1) = -2 -> negative, skip.
update min_so_far = min(-1, -3) = -3.
freq[-3]=1.
So ans=0. Correct because no subarray sum is Fibonacci.
What about nums = [-1, 1]? We did earlier and got ans=2.
P=[0,-1,0]
min_so_far=0
k=1: P[1]=-1, threshold=-1-0=-1 -> skip.
min_so_far = min(0,-1) = -1.
freq[-1]=1.
k=2: P[2]=0, threshold=0 - (-1)=1 >=0.
sorted_fib for max_diff=1: [0,1].
f=0: target=0 -> in freq? freq has {0:1, -1:1}? But wait, we have added P[1]=-1. So freq[0]=1 (from P[0]) and also we are about to add P[2]=0 later. But during the inner loop, we have freq: {0:1, -1:1}. So target=0 is in freq -> ans+=1.
f=1: 1<=1 -> target=-1 -> in freq -> ans+=1 (total 2)
then break because next? No next.
Then update min_so_far: min(-1,0) = -1.
freq[0] becomes 2.
So ans=2. Correct.
So the algorithm with the threshold break seems correct.
But wait: in the example above, for k=2, we have threshold=1. We considered f=0 and f=1. That's correct.
However, what if the array is [0,0]?
P=[0,0,0]
max_diff=0, fib_set={0}, sorted_fib=[0].
min_so_far=0
k=1: P[1]=0, threshold=0-0=0 >=0.
f=0: target=0 -> in freq (freq{0:1}) -> ans+=1.
then break? f=0 is the only one.
update min_so_far: min(0,0)=0.
freq[0]=2.
k=2: P[2]=0, threshold=0-0=0.
f=0: target=0 -> in freq (freq{0:2}) -> ans+=2 (total 3).
update min_so_far=0.
freq[0]=3.
So ans=3. Correct.
So we'll go with this optimized version.
But note: we are using threshold = P[k] - min_so_far. What if min_so_far is not the minimum of P[0..k-1]? We are updating it after the inner loop. That's correct because during the inner loop, min_so_far is the minimum of P[0..k-1]. And we update it after we have processed k, so for the next k, it will be the minimum of P[0..k].
However, what about the case when P[k] is the new minimum? Then after we update, min_so_far becomes P[k]. But during the inner loop for the next k, we will use the updated min_so_far. That's correct.
So the algorithm is:
def count_fib_subarrays(nums):
n = len(nums)
if n == 0:
return 0
P = [0]*(n+1)
for i in range(n):
P[i+1] = P[i] + nums[i]
minP = min(P)
maxP = max(P)
max_diff = maxP - minP
# Generate Fibonacci set up to max_diff
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a+b
sorted_fib = sorted(fib_set)
from collections import defaultdict
freq = defaultdict(int)
freq[0] = 1
ans = 0
min_so_far = 0 # minimum of P[0..k-1], initially P[0]=0
for k in range(1, n+1):
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
# update min_so_far and freq for P[k]
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] += 1
return ans
Let's test with a case where the array has negative numbers and the prefix sums become negative and then positive.
Example: nums = [2, -1, 2]
P=[0,2,1,3]
minP=0, maxP=3, max_diff=3.
fib_set: {0,1,2,3} (since Fibonacci up to 3: 0,1,1,2,3 -> set: {0,1,2,3})
sorted_fib=[0,1,2,3]
min_so_far=0
freq: {0:1}
k=1: P[1]=2, threshold=2-0=2>=0.
f=0: target=2 -> not in freq.
f=1: target=1 -> not.
f=2: target=0 -> in freq -> ans+=1.
f=3: 3>2 -> break.
update min_so_far: min(0,2)=0.
freq[2]=1.
k=2: P[2]=1, threshold=1-0=1>=0.
f=0: target=1 -> not in freq (freq: {0:1,2:1})
f=1: target=0 -> in freq -> ans+=1 (total 2)
f=2: 2>1 -> break.
update min_so_far: min(0,1)=0.
freq[1]=1.
k=3: P[3]=3, threshold=3-0=3>=0.
f=0: target=3 -> not.
f=1: target=2 -> in freq (freq: {0:1,2:1,1:1}) -> ans+=1 (total 3)
f=2: target=1 -> in freq -> ans+=1 (total 4)
f=3: target=0 -> in freq -> ans+=1 (total 5)
then break? next f? none.
update min_so_far: min(0,3)=0.
freq[3]=1.
So ans=5.
Subarrays:
[2]: sum=2 -> Fibonacci.
[-1]: sum=-1 -> not.
[2]: sum=2 -> Fibonacci? But wait, the third element is 2, so [2] at index2 -> sum=2.
[2,-1]: sum=1 -> Fibonacci.
[-1,2]: sum=1 -> Fibonacci.
[2,-1,2]: sum=3 -> Fibonacci.
So we have: [2] (first), [2] (third), [2,-1], [-1,2], [2,-1,2] -> that's 5. Correct.
So it works.
But wait: what about the subarray [2] at index0? We counted it when k=1 and i=0? Actually, for k=1, we have P[1]=2, and we found target=0 with f=2. That corresponds to i=0 and k=1, which is subarray [0:0] -> the first element. So that's [2]. Correct.
What about [2] at index2? That is when k=3 and i=2? But we don't have i=2 and k=3? Actually, for k=3, we are considering i from 0 to 2. We had:
f=1: target=2 -> which is P[?] = 2. We have P[1]=2. So that corresponds to i=1 and k=3? That gives subarray [1:2] which is [-1,2]? Wait, let's map:
subarray from i to j: sum = P[j+1] - P[i]. So if we have i and k such that P[k] - P[i] = f.
For k=3, P[3]=3.
We had f=1 -> target=2. So P[i]=2. Which i? We have P[1]=2. So i=1, then subarray is from index i to j = k-1 = 2? That is [1:2] -> nums[1] and nums[2] -> [-1,2]. That's one subarray.
f=2 -> target=1 -> P[i]=1 -> i=2? But we haven't added P[2] at the time of k=3? Wait, we are at k=3, and we have in freq the prefix sums for indices 0,1,2. So P[2]=1 is in freq. So i=2 gives subarray [2:2] -> the third element [2]. Correct.
f=3 -> target=0 -> P[i]=0 -> i=0 gives subarray [0:2] -> all three.
So we counted [2] at index2 via f=2? Actually, f=2 gives target=1, and we have P[2]=1. So that's i=2 and k=3 -> subarray [2:2]. Correct.
And we also counted [2] at index0 via k=1 and f=2? That was i=0 and k=1.
So we have two single-element subarrays of 2.
So total 5.
So the algorithm is correct.
Now, we should consider the possibility of integer overflow? In Python, no.
But what if the array is very long and the prefix sums are huge? The Fibonacci generation might take time? But it's only up to max_diff, which is the range of prefix sums. And the number of Fibonacci numbers is logarithmic.
However, if max_diff is huge, say 10^100, then generating Fibonacci numbers up to that might require about 500 iterations, which is fine.
But what if max_diff is negative? That can't happen because max_diff = maxP - minP >=0.
So we are good.
Let's write the final code.
One more thing: what if the array has only one element and it's 0? We tested that.
What if the array has a mix of positive and negative and the prefix sums oscillate? Our min_so_far will update accordingly.
I think it's solid.
We'll return the count.
But note: the problem says "number of fibonacci subarrays". So we return an integer.
Let's code accordingly.
However, note: the Fibonacci set generation might include numbers that are not needed if max_diff is small. But that's fine.
We'll implement and test with a few more examples.
Example: nums = [1,4]
P=[0,1,5]
max_diff=5, fib_set up to 5: {0,1,2,3,5}? Fibonacci: 0,1,1,2,3,5. So set: {0,1,2,3,5}.
sorted_fib=[0,1,2,3,5]
min_so_far=0
freq={0:1}
k=1: P[1]=1, threshold=1.
f=0: target=1 -> not in freq.
f=1: target=0 -> in freq -> ans=1.
f=2: 2>1 -> break.
min_so_far=0, freq[1]=1.
k=2: P[2]=5, threshold=5.
f=0: target=5 -> not.
f=1: target=4 -> not.
f=2: target=3 -> not.
f=3: target=2 -> not.
f=5: target=0 -> in freq -> ans=2.
So ans=2.
Subarrays: [1] (sum=1) and [1,4] (sum=5). Both Fibonacci. Correct.
Example: nums = [4]
P=[0,4]
max_diff=4, fib_set: {0,1,2,3}? Fibonacci up to 4: 0,1,1,2,3. So set: {0,1,2,3}.
sorted_fib=[0,1,2,3]
k=1: P[1]=4, threshold=4.
f=0: target=4 -> not.
f=1: target=3 -> not.
f=2: target=2 -> not.
f=3: target=1 -> not.
f= next? none.
ans=0. Correct.
Example: nums = [3]
P=[0,3]
fib_set up to 3: {0,1,2,3}
k=1: threshold=3.
f=0: target=3 -> not.
f=1: target=2 -> not.
f=2: target=1 -> not.
f=3: target=0 -> in freq -> ans=1.
So correct.
Example: nums = [0,0,0]
P=[0,0,0,0]
max_diff=0, fib_set={0}
sorted_fib=[0]
min_so_far=0
freq={0:1}
k=1: P[1]=0, threshold=0.
f=0: target=0 -> in freq -> ans=1.
update min_so_far=0, freq[0]=2.
k=2: P[2]=0, threshold=0.
f=0: target=0 -> in freq (freq[0]=2) -> ans+=2 (total 3).
update min_so_far=0, freq[0]=3.
k=3: P[3]=0, threshold=0.
f=0: target=0 -> in freq (freq[0]=3) -> ans+=3 (total 6).
update min_so_far=0, freq[0]=4.
So ans=6.
Subarrays of [0,0,0]:
length1: 3
length2: 2
length3: 1
total 6. All have sum 0. Correct.
So it works.
We'll return the function.
But wait: what about the Fibonacci number 1? We have it. And 0.
What about negative Fibonacci numbers? We don't consider them.
So final code:
Note: We must be cautious about the generation of Fibonacci numbers. We start with a=0, b=1 and then while a<=max_diff: add a and then a,b = b, a+b. This will generate 0,1,1,2,3,... until a exceeds max_diff.
But what if max_diff is 0? Then we add a=0, then set a=1, b=1, then since a=1>0, we break. So set={0}. Good.
What if max_diff is 1? Then:
a=0 -> add 0 -> set={0}
then a=1, b=1 -> a=1<=1 -> add 1 -> set={0,1}
then a=1, b=2 -> a=1<=1 -> add 1 again? But set will have {0,1}. Then a=2, b=3 -> a=2>1 -> break.
So set={0,1}. Good.
So it's correct.
We'll implement accordingly.
Let's write the function.
To solve this problem, we need to count the number of contiguous subarrays in a given integer array where the sum of the subarray is a Fibonacci number. The solution involves efficiently checking all possible subarray sums against a precomputed set of Fibonacci numbers up to the maximum possible subarray sum.
Approach
-
Prefix Sum Calculation: Compute the prefix sums of the array to quickly determine the sum of any subarray. The sum of subarray nums[i..j] is P[j+1] - P[i], where P is the prefix sum array with P[0] = 0.
-
Determine Maximum Difference: Find the minimum and maximum values in the prefix sum array. The maximum possible subarray sum (difference between two prefix sums) is maxP - minP. This helps in bounding the Fibonacci numbers we need to consider.
-
Generate Fibonacci Numbers: Generate all Fibonacci numbers up to max_diff (inclusive) and store them in a set for O(1) lookups. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
-
Count Valid Subarrays: Use a frequency map to keep track of prefix sums encountered so far. For each current prefix sum P[k], iterate over all Fibonacci numbers f and check if P[k] - f exists in the frequency map (i.e., there exists a previous prefix sum P[i] such that P[k] - P[i] = f). The count of such P[i] values gives the number of valid subarrays ending at k-1. To optimize, we sort the Fibonacci numbers and break early when f exceeds P[k] - min_so_far, where min_so_far is the minimum prefix sum encountered so far.
Solution Code
from collections import defaultdict
def count_fib_subarrays(nums):
n = len(nums)
if n == 0:
return 0
# Compute prefix sums
P = [0] * (n + 1)
for i in range(n):
P[i+1] = P[i] + nums[i]
minP = min(P)
maxP = max(P)
max_diff = maxP - minP
# Generate Fibonacci numbers up to max_diff
fib_set = set()
a, b = 0, 1
while a <= max_diff:
fib_set.add(a)
a, b = b, a + b
sorted_fib = sorted(fib_set)
freq = defaultdict(int)
freq[0] = 1 # P[0] = 0
ans = 0
min_so_far = 0 # minimum of P[0..k-1]
for k in range(1, n+1):
threshold = P[k] - min_so_far
if threshold >= 0:
for f in sorted_fib:
if f > threshold:
break
target = P[k] - f
if target in freq:
ans += freq[target]
if P[k] < min_so_far:
min_so_far = P[k]
freq[P[k]] += 1
return ans
Explanation
-
Prefix Sums: The prefix sum array P is built such that P[i] holds the sum of the first i elements of nums. This allows O(1) computation of any subarray sum.
-
Fibonacci Set: All Fibonacci numbers up to max_diff (the range of possible subarray sums) are generated and stored in a set for quick membership checks. The generation starts from 0 and 1, extending until the next Fibonacci number exceeds max_diff.
-
Frequency Map: As we iterate through the prefix sums, we maintain a frequency map of previously seen prefix sums. For each current prefix sum P[k], we check for every Fibonacci number f if P[k] - f exists in the map. If it does, it means there is a subarray ending at k-1 whose sum is f.
-
Optimization with Threshold: By tracking the minimum prefix sum encountered so far (min_so_far), we can limit the Fibonacci numbers to consider. Only Fibonacci numbers f such that f <= P[k] - min_so_far need to be checked, because for larger f, P[k] - f would be less than min_so_far and thus not present in the frequency map. This reduces the number of checks per iteration.
-
Complexity: The algorithm runs in O(n log M) time, where n is the array length and M is max_diff. The space complexity is O(n) for storing prefix sums and the frequency map. The logarithmic factor comes from the number of Fibonacci numbers up to max_diff, which is approximately O(log M) due to exponential growth of Fibonacci numbers.