509. Fibonacci Number

Fibonacci Number (LeetCode 509) is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Dynamic Programming (DP) Patterns pattern, in the 1D Array (Fibonacci Style) subpattern.

How to solve Fibonacci Number

Fibonacci Number is a Fibonacci Style DP problem, part of Dynamic Programming (DP) Patterns. Solve problems with Fibonacci-like recurrence: climbing stairs, house robber, decode ways.

Work towards the solution in these steps:

  1. Hint 1: The Fibonacci sequence is defined recursively: F(n) = F(n-1) + F(n-2).
  2. Hint 2: A naive recursive solution works but is inefficient due to repeated calculations.
  3. Hint 3: Use memoization or dynamic programming to store previously computed values.

The reference solution runs in O(logn) time and O(1) space.

The Fibonacci Number solution and editorial walks through the full approach with reference code.

Problem statement

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Example 1:

Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints:

- 0 <= n <= 30

Topics and companies

Topics: Math, Dynamic Programming, Recursion, Memoization.

Reported in interviews at JPMorgan, Amazon, Google, Apple, Facebook.

How to practise Fibonacci Number on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(logn) time and O(1) space.

Open Fibonacci Number in the code editor, or read the Fibonacci Number editorial for a worked solution with its approach and complexity analysis.

Where Fibonacci Number sits in the DSA pattern sheet

Problems related to Fibonacci Number

Other problems that use the same 1D Array (Fibonacci Style) and Dynamic Programming (DP) Patterns techniques:

Fibonacci Number FAQ

What is the LeetCode number of Fibonacci Number?

Fibonacci Number is LeetCode problem 509, rated Easy.

What pattern is used to solve Fibonacci Number?

Fibonacci Number is a Fibonacci Style DP problem. It belongs to the Dynamic Programming (DP) Patterns pattern, in the 1D Array (Fibonacci Style) subpattern.

What is the time complexity of Fibonacci Number?

The reference solution runs in O(logn) time and O(1) space.

Which companies ask Fibonacci Number?

Fibonacci Number has been reported in interviews at JPMorgan, Amazon, Google, Apple, Facebook.

Preparing this workspace.