← DiffPush

Find the Nth Fibonacci Number

Baseline Dynamic Programming · Intro to DP O(n) · O(1)

The Beacon Pulse Ledger

A deep-space relay logs how many beacons are airborne each hour, and the count always follows a Fibonacci-style drift: each hour's total is the sum of the two previous hours' totals. Mission control wants to forecast the count for any hour N without replaying the whole log. Your job is to compute the Nth value in this pulse series, where hour 0 counts 0 beacons and hour 1 counts 1.

Input: A single integer n, the hour index to forecast.

Output: Return the nth number of the sequence defined by f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2).

Constraints

Examples

Example 1

Input: {"n":5}
Output: 5
The series runs 0, 1, 1, 2, 3, 5 — the fifth value is 5.

Example 2

Input: {"n":10}
Output: 55
Continuing the series: 8 + 13 = 21, 13 + 21 = 34, 21 + 34 = 55.

Solve this in your browser →

Also on LeetCode ↗