VOOZH about

URL: https://www.geeksforgeeks.org/dsa/padovan-sequence/

⇱ Padovan Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Padovan Sequence

Last Updated : 26 May, 2026

A Padovan Sequence is a sequence similar to Fibonacci sequence which is represented by the following recurrence relation:
P(n) = P(n - 2) + P(n - 3)
P(0) = P(1) = P(2) = 1 

First few terms of the sequence are 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37,.....  Spiral of equilateral triangles with side lengths which follow the Padovan sequence. 

šŸ‘ 2056958170

Given a number n, find the nth number in the Padovan Sequence. Since the output may be too large, compute the answer modulo 10^9 + 7.

Examples:

Input: n = 4
Output: 2
Explanation: P(4) = P(2) + P(1) = 1 + 1 = 2

Input: n = 7
Output: 5
Explanation:
P(7) = P(5) + P(4) = P(3) + P(2) + P(2) + P(1)
= P(1) + P(0) + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1 = 5

[Naive Approach] Using Recursion - O(2 ^ n) Time and O(n) Space

  • If n ≤ 2, return 1 (base case of the sequence).
  • Define the recurrence relation: P(n) = P(nāˆ’2) + P(nāˆ’3).
  • Recursively compute P(nāˆ’2) and P(nāˆ’3) by calling the same function.
  • Add both results to get P(n).
  • Return the final computed value.

Output
5
šŸ‘ p_7_
Explanation using recursive tree(highlighted states showing overlapping sub-problems)

[Expected Approach] Using Dynamic Programming(DP) - O(n) Time and O(n) Space

A naive recursive approach recalculates the same subproblems many times, leading to exponential time complexity. Dynamic Programming avoids this by storing already computed values in a table (dp array) and building the answer in a bottom-up manner. This converts the solution into a linear time process by ensuring each state is computed only once.

  • If n ≤ 2, return 1 as base cases.
  • Initialize a DP array dp[0...n] and set dp[0] = dp[1] = dp[2] = 1.
  • Iterate from i = 3 to n.
  • For each i, compute: dp[i] = dp[i-2] + dp[i-3] (mod 1e9+7).
  • Return dp[n] as the final answer.

Consider the following dry run for better understanding: n = 10

  • Base cases: dp[0] = 1, dp[1] = 1, dp[2] = 1
  • dp[3] = dp[1] + dp[0] = 1 + 1 = 2
  • dp[4] = dp[2] + dp[1] = 1 + 1 = 2
  • dp[5] = dp[3] + dp[2] = 2 + 1 = 3
  • dp[6] = dp[4] + dp[3] = 2 + 2 = 4
  • dp[7] = dp[5] + dp[4] = 3 + 2 = 5
  • dp[8] = dp[6] + dp[5] = 4 + 3 = 7
  • dp[9] = dp[7] + dp[6] = 5 + 4 = 9
  • dp[10] = dp[8] + dp[7] = 7 + 5 = 12

Final answer : 12


Output
5
Comment