EasyDynamic ProgrammingRecursionMemoizationMath

2 approaches, code in every language

Problem description

The Fibonacci numbers start with F(0) = 0 and F(1) = 1, and after that every number is the sum of the two immediately before it: F(n) = F(n - 1) + F(n - 2) for n greater than 1.

Given an index n, return the value F(n).

Example 1

Input: n = 2

Output: 1

F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2

Input: n = 5

Output: 5

The sequence up to index 5 is 0, 1, 1, 2, 3, 5, so F(5) = 5.

Constraints

  • 0 ≤ n ≤ 30
  • The result fits inside a signed 32-bit integer.

After the pattern

Now solve one you haven't seen.

Cascade Register Reading is our own problem on the technique behind Fibonacci Number: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free