Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find the Nth Fibonacci Number Efficiently

Basic Acceptance 85.25% Points 10.00

You are given an integer n. Your task is to return the nth Fibonacci number using an efficient approach.

The Fibonacci sequence starts with F(1) = 0 and F(2) = 1. Each subsequent term is calculated as the sum of the previous two terms.

Examples
Example 1

Input: n = 10

Output: 34

Explanation: The 10th term of the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 is 34.

Example 2

Input: n = 1

Output: 0

Explanation: The first Fibonacci number is 0.

Example 3

Input: n = 5

Output: 3

Explanation: The 5th term of the Fibonacci sequence is 3.

Constraints
  • 1 <= n <= 90
Companies
Samsung Infosys
Topics
Data Structures Basics Recursion Dynamic Programming + 1 more
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions