Tensorum
YouTubeसीखना शुरू करें
LeetCode 873 · LIS

Length of Longest Fibonacci Subsequence

LeetCode 873 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Two numbers fix the whole sequence — extend each pair with a set lookup.

मध्यमArrayHash TableDynamic Programming

मैंने Length of Longest Fibonacci Subsequence (LeetCode 873) ऐसे हल किया — LIS पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

A Fibonacci-like sequence is fully determined by its first two numbers. So try every pair (i, j) as the start and keep stepping: the next value must be the sum of the last two, and a hash set tells you instantly whether it exists.

Approach

  1. 1

    Put all values in a set.

  2. 2

    For each pair i < j, start with length 2.

  3. 3

    While prev + cur is in the set, shift forward and grow the length.

  4. 4

    Keep the best; a best of 2 means no valid sequence, so return 0.

मैंने कैसे हल किया

Pair start + set extensionPythonO(n² log M) time · O(n) space
class Solution:
    def lenLongestFibSubseq(self, nums: List[int]) -> int:
        n=len(nums)
        prev=None
        cur =None
        next=None
        maxlength=0
        numset=set(nums)
        for i in range(n):
            for j in range(i+1,n):
                prev=nums[i]
                cur=nums[j]
                next=nums[i]+nums[j]
                curLength=2
                while next in numset:
                    curLength+=1
                    prev=cur
                    cur=next
                    next=prev+cur
                maxlength=max(maxlength,curLength)
        return 0 if maxlength==2 else maxlength

स्टेप-थ्रू लोड हो रहा है…

Length of Longest Fibonacci Subsequence — अक्सर पूछे जाने वाले प्रश्न

Length of Longest Fibonacci Subsequence के पीछे intuition क्या है?

A Fibonacci-like sequence is fully determined by its first two numbers. So try every pair (i, j) as the start and keep stepping: the next value must be the sum of the last two, and a hash set tells you instantly whether it exists.

Length of Longest Fibonacci Subsequence (LeetCode 873) कैसे हल करें?

1. Put all values in a set. 2. For each pair i < j, start with length 2. 3. While prev + cur is in the set, shift forward and grow the length. 4. Keep the best; a best of 2 means no valid sequence, so return 0.

Length of Longest Fibonacci Subsequence की time और space complexity क्या है?

Time: O(n² · log M) (each chain grows like Fibonacci)। Space: O(n)। (Accepted approach: Pair start + set extension।)

Length of Longest Fibonacci Subsequence में आम गलतियाँ क्या हैं?

Length 2 alone doesn't count — the answer must be at least 3 or 0. A DP over (j, k) pairs gives O(n²) exactly if needed.