#3708

Longest Fibonacci Subarray

Medium
ArrayHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use a single pass to check the Fibonacci condition, leveraging the fact that any two elements can start a Fibonacci sequence.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize length to 2 (since any two elements form a Fibonacci sequence).
  2. 2Step 2: Iterate through the array starting from the third element.
  3. 3Step 3: If the current element equals the sum of the two preceding elements, increase the length; otherwise, reset it to 2.
solution.py10 lines
1def lenLongestFibSubarray(nums):
2    max_len = 2
3    current_len = 2
4    for i in range(2, len(nums)):
5        if nums[i] == nums[i - 1] + nums[i - 2]:
6            current_len += 1
7            max_len = max(max_len, current_len)
8        else:
9            current_len = 2
10    return max_len if max_len >= 3 else 0

Complexity note: Single pass through the array results in linear time complexity.

  • 1Any two elements can start a Fibonacci sequence.
  • 2Resetting the length to 2 helps track valid sequences efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.