Meta Data#
Difficulty: medium First Attempt: 2025-10-11
- Submissions: Accepted (first try)
Approach#
For a contiguous run, track only the current length (Array Template 1). Any two adjacent numbers can start a new Fibonacci subarray, so a break resets the length to 2, not 1.
My Solution#
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
if n <= 2:
return n
cur = best = 2
for i in range(2, n):
cur = cur + 1 if nums[i] == nums[i - 1] + nums[i - 2] else 2
best = max(best, cur)
return best
Complexity#
Time O(n), space O(1).
Mistakes to Avoid#
- A break resets to 2, since the last two numbers start a new run.
- With fewer than 3 elements, return the length.
Interview Explanation#
From the third number on, I extend the current length when it equals the sum of the previous two, otherwise restart from the last two with length 2. Time O(n).
