Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Fibonacci Number problem solution

YASH PAL, 31 July 202422 January 2026

In this Leetcode Fibonacci Number problem solution 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).

Leetcode Fibonacci Number problem solution

Leetcode Fibonacci Number problem solution in Python.

class Solution:
    def fib(self, N: int) -> int:
        if N == 0:
            return 0
        if N == 1:
            return 1
        curr_n = 2
        n_1 = 1
        n_2 = 0
        
        while N>=curr_n:
            ans = n_1 + n_2
            n_2=n_1
            n_1=ans
            curr_n+=1
        return ans

Fibonacci Number problem solution in Java.

public int fib(int N) {
    if(N == 1) return 1;
    if(N == 0) return 0;
    return fib(N-1)+fib(N-2);
}

Problem solution in C++.

public:
    int fib(int N) {
        if(N < 2){
            return N;
        }
        vector vals = {0, 1};
        
        int i = 2;
        int sum = 1;
        while(i <= N){
            sum = vals[i-1] + vals[i-2];
            vals.push_back(sum);
            i++;
        }
        
        return sum;
    }
};

Problem solution in C.

int calculate_fib(int N, int *cache)
{
    if (N == 1 || N == 0)
        return (N);
    if (cache[N - 1] != 0)
        return (cache[N - 1]);
    cache[N - 1] = calculate_fib(N - 1, cache) + calculate_fib(N - 2, cache);
    return (cache[N - 1]);
}

int fib(int N){
    int *cache;
    int r;
    int i;
    
    i = -1;
    cache = (int *)malloc(sizeof(int) * N);
    while (++i < N)
        cache[i] = 0;
    r = calculate_fib(N, cache);
    free(cache);
    return (r);
}

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes