VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-prefix-subsequence-matching-fibonacci-sequence/

⇱ Longest Prefix Subsequence matching Fibonacci Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Prefix Subsequence matching Fibonacci Sequence

Last Updated : 23 Jul, 2025

Given an array arr of size N. Also, there is another array B of the infinite size where B[0] = B[1] = 1, and for all (i >= 2), B[i] = B[i-1]+B[i-2], the task is to find the length of the longest subsequence which is the prefix of array B. If there is no subsequence which is the prefix of array B then return 0.

Examples:

Input: N = 6, arr = {1, 2, 3, 1, 2, 3}
Output: 4
Explanation: Subsequence {1,1,2,3} which is a prefix array of B of length 4.

Input: N = 5, arr = {2, 3, 1, 2, 5}
Output: 1
Explanation: Subsequence {1} which is a prefix array of B of length 1.

Approach: To solve the problem follow the below idea:

Using Dynamic Programming, we can iterate over both the arrays A and B, and see the total common length until A length is finished.

Below are the steps involved:

  • Create an array dp as B of length A where each element is as dp[i] = dp[i - 1] + dp[i-2].
  • Iterate over both the arrays:
    • If(A[i] == B[j])
      • count++, increase the lcs.
    • Otherwise, increase i++, As the prefix of B should be matched.

Below is the implementation of the code:


Output
4

Time Complexity: O (N + M)
Auxiliary Space: O(N)

Comment