Tutorialspoint
Problem
Solution
Submissions

Implement a Recursive Function for Fibonacci Numbers

Certification: Intermediate Level Accuracy: 100% Submissions: 2 Points: 10

Write a Python function that computes the nth Fibonacci number using recursion. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.

Example 1
  • Input: 6
  • Output: 8
  • Explanation:
    • Step 1: Take the input number 6.
    • Step 2: Calculate the Fibonacci sequence up to the 6th number: 0, 1, 1, 2, 3, 5, 8.
    • Step 3: Return the 6th Fibonacci number, which is 8.
Example 2
  • Input: 10
  • Output: 55
  • Explanation:
    • Step 1: Take the input number 10.
    • Step 2: Calculate the Fibonacci sequence up to the 10th number: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.
    • Step 3: Return the 10th Fibonacci number, which is 55.
Constraints
  • 0 ≤ n ≤ 35 (higher values may cause performance issues due to recursion)
  • Return the nth Fibonacci number (0-indexed)
  • Time Complexity: O(2^n) for naive recursion, O(n) with memoization
  • Space Complexity: O(n) due to the recursion stack
Control StructuresRecursionWalmartSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Base cases: if n is 0, return 0; if n is 1, return 1
  • Recursive case: return fibonacci(n-1) + fibonacci(n-2)
  • Consider using memoization to optimize performance
  • Try implementing with a dictionary to cache results

Steps to solve by this approach:

 Step 1: Define the base cases for the Fibonacci sequence

 Step 2: Handle n = 0 by returning 0
 Step 3: Handle n = 1 by returning 1
 Step 4: For n > 1, use the recursive formula: F(n) = F(n-1) + F(n-2)
 Step 5: Make recursive calls to fibonacci(n-1) and fibonacci(n-2)
 Step 6: Add the results of the recursive calls
 Step 7: Return the sum as the nth Fibonacci number

Submitted Code :