0% found this document useful (0 votes)
4 views4 pages

coding_Questioninteriew_basic

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

coding_Questioninteriew_basic

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Q1.

Fibonaci series- three Aproach


1.Recursion
2.Space with loop
3.Optimize Space through swaping
Description :
509. Fibonacci Number
Easy
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

Solution:-
1. recursion
class Solution {
public int fib(int n) {
if(n==0)
{
return 0;
}
if(n==1)
{
return 1;
}
return fib(n-1)+fib(n-2);
}}
2. loop with extra space

class Solution {
public int fib(int n) {

if(n==0)
{
return 0;

}
if(n==1)
{
return 1;
}
int fib[]=new int [n+1];
fib[0]=0;
fib[1]=1;
for(int i=2;i<=n;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
return fib[n];
}}

3. optimizing space through swapping

class Solution {
public int fib(int n) {

if(n==0)
{
return 0;
}
int slast=0;
int last=1;
int temp=0;

for(int i=2;i<=n;i++) {

temp=last+slast;
slast=last;
last=temp;

}
return temp;
//return fib[n];
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy