↓Skip to main content
  1. LeetCode/

LeetCode 3708: Longest Fibonacci Subarray

·1 min· ·
LeetCode Medium Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

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).

Related

LeetCode 3689: Maximum Total Subarray Value I
·1 min
LeetCode Medium Greedy Array
LeetCode 3689 note: the same subarray may be chosen repeatedly, and the whole array’s max minus min is the best single value, so choose it k times
LeetCode 2294: Partition Array Such That Maximum Difference Is K
·1 min
LeetCode Medium Greedy Sorting Array
LeetCode 2294 note: subsequences ignore order, so sort and extend each group from its minimum until a value exceeds min + k
LeetCode 1493: Longest Subarray of 1's After Deleting One Element
·2 mins
LeetCode Medium Sliding-Window Dynamic-Programming Array
LeetCode 1493 note: find the longest window with at most one 0; since one element must be deleted, the answer is the window length minus 1
LeetCode 3195: Find the Minimum Area to Cover All Ones I
·1 min
LeetCode Medium Array Matrix
LeetCode 3195 note: track the topmost, bottommost, leftmost and rightmost 1; the area is height times width
LeetCode 3649: Number of Perfect Pairs
·2 mins
LeetCode Medium Two-Pointers Math Sorting Array
LeetCode 3649 note: simplify the condition to “larger absolute value <= 2 × smaller absolute value”, then count with two pointers over sorted absolute values
LeetCode 1222: Queens That Can Attack the King
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 1222 note: step outward from the king in eight directions; the first queen met in each direction can attack, with queens in a set for lookups