└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # Top 35 Fibonacci Sequence Interview Questions in 2025
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | #### You can also find all 35 answers here 👉 [Devinterview.io - Fibonacci Sequence](https://devinterview.io/questions/data-structures-and-algorithms/fibonacci-sequence-interview-questions)
11 |
12 |
13 |
14 | ## 1. What is the _Fibonacci sequence_?
15 |
16 | The **Fibonacci Sequence** is a series of numbers where each number $F(n)$ is the sum of the two preceding ones, often starting with 0 and 1. That is:
17 |
18 | $$
19 | F(n) = F(n-1) + F(n-2)
20 | $$
21 |
22 | with initial conditions
23 |
24 | $$
25 | F(0) = 0, \quad F(1) = 1
26 | $$
27 |
28 | ### Golden Ratio
29 |
30 | The ratio of consecutive Fibonacci numbers approximates the Golden Ratio ($\phi \approx 1.6180339887$):
31 |
32 | $$
33 | \lim_{{n \to \infty}} \frac{{F(n+1)}}{{F(n)}} = \phi
34 | $$
35 |
36 | ### Real-World Occurrences
37 |
38 | The sequence frequently manifests in nature, such as in flower petals, seedhead spirals, and seashell growth patterns.
39 |
40 | ### Visual Representation
41 |
42 | 
43 |
44 | ### Code Example: Calculating The Nth Fibonacci Number
45 |
46 | Here is the Python code:
47 |
48 | ```python
49 | # Using recursion
50 | def fibonacci_recursive(n):
51 | if n <= 0: return 0
52 | elif n == 1: return 1
53 | return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
54 |
55 | # Using dynamic programming for efficiency
56 | def fibonacci_dynamic(n):
57 | fib = [0, 1]
58 | for i in range(2, n+1):
59 | fib.append(fib[-1] + fib[-2])
60 | return fib[n]
61 | ```
62 |
63 |
64 | ## 2. Write a function to calculate the _nth Fibonacci number_ using a _recursive_ approach.
65 |
66 | ### Problem Statement
67 |
68 | The task is to write a function that **returns the $n$th Fibonacci number** using a **recursive approach**.
69 |
70 | ### Solution
71 |
72 | The **naive recursive** solution for the Fibonacci series, while easy to understand, is inefficient due to its exponential time complexity of $O(2^n)$.
73 |
74 | **Dynamic Programming** methods like memoization and tabulation result in optimized time complexity.
75 |
76 | #### Algorithm Steps
77 |
78 | 1. Check for the base cases, i.e., if $n$ is 0 or 1.
79 | 2. If not a base case, **recursively** compute $F(n-1)$ and $F(n-2)$.
80 | 3. Return the sum of the two recursive calls.
81 |
82 | #### Implementation
83 |
84 | Here is the Python code:
85 |
86 | ```python
87 | def fib_recursive(n):
88 | if n <= 1:
89 | return n
90 | return fib_recursive(n-1) + fib_recursive(n-2)
91 | ```
92 |
93 | #### Complexity Analysis
94 |
95 | - **Time Complexity**: $O(2^n)$. This is due to the two recursive calls made at each level of the recursion tree, resulting in an exponential number of function calls.
96 |
97 | - **Space Complexity**: $O(n)$. Despite the inefficient time complexity, the space complexity is $O(n)$ as it represents the depth of the recursion stack.
98 |
99 |
100 | ## 3. Provide a non-recursive implementation for generating the _Fibonacci sequence_ to the _nth number_.
101 |
102 | ### Problem Statement
103 |
104 | The task is to **generate** the Fibonacci sequence to the $n$th number using a **non-recursive approach**.
105 |
106 | ### Solution
107 |
108 | While recursion offers a straightforward solution for the Fibonacci sequence, it has performance and stack overflow issues. A **non-recursive** approach, often based on a **loop** or **iterative method**, overcomes these limitations.
109 |
110 | Here, I'll present both **binet's formula** and an **iterative method** as the non-recursive solutions.
111 |
112 | #### Binet's Formula
113 |
114 | $$
115 | F(n) = \frac{{\phi^n - \psi^n}}{{\sqrt 5}}
116 | $$
117 |
118 | where:
119 |
120 | - $\phi = \frac{{1 + \sqrt 5}}{2}$ (the golden ratio)
121 | - $\psi = \frac{{1 - \sqrt 5}}{2}$
122 |
123 | #### Algorithm Steps
124 |
125 | 1. Compute $\phi$ and $\psi$.
126 | 2. Plug values into the formula for $F(n)$.
127 |
128 | #### Complexity Analysis
129 |
130 | - **Time Complexity**: $O(1)$
131 | - **Space Complexity**: $O(1)$
132 |
133 | **Note**: While Binet's formula offers an elegant non-recursive solution, it's sensitive to **floating-point errors** which can impact accuracy, especially for large $n$.
134 |
135 | #### Iterative Method
136 |
137 | #### Algorithm Steps
138 |
139 | 1. Initialize $\text{prev} = 0$ and $\text{curr} = 1$. These are the first two Fibonacci numbers.
140 | 2. For $i = 2$ to $n$, update $\text{prev}$ and $\text{curr}$ to be $\text{prev} + \text{curr}$ and $\text{prev}$ respectively. These become the next numbers in the sequence.
141 |
142 | #### Complexity Analysis
143 |
144 | - **Time Complexity**: $O(n)$
145 | - **Space Complexity**: $O(1)$
146 |
147 | #### Implementation
148 |
149 | Here's the Python code for both methods:
150 |
151 | ### Binet's Formula
152 |
153 | ```python
154 | import math
155 |
156 | def fib_binet(n):
157 | phi = (1 + math.sqrt(5)) / 2
158 | psi = (1 - math.sqrt(5)) / 2
159 | return int((phi**n - psi**n) / math.sqrt(5))
160 |
161 | # Output
162 | print(fib_binet(5)) # Output: 5
163 | ```
164 |
165 | ### Iterative Method
166 |
167 | ```python
168 | def fib_iterative(n):
169 | if n <= 1:
170 | return n
171 | prev, curr = 0, 1
172 | for _ in range(2, n + 1):
173 | prev, curr = curr, prev + curr
174 | return curr
175 |
176 | # Output
177 | print(fib_iterative(5)) # Output: 5
178 | ```
179 |
180 | Both functions will return the 5th Fibonacci number.
181 |
182 |
183 | ## 4. What is the _time complexity_ of the recursive Fibonacci solution, and how can this be improved?
184 |
185 | The **naive recursive** implementation of the Fibonacci sequence has a time complexity of $O(2^n)$, which can be optimized using techniques such as **memoization** or employing an **iterative approach**.
186 |
187 | ### Naive Recursive Approach
188 |
189 | This is the straightforward, but inefficient, method.
190 |
191 | #### Algorithm
192 |
193 | 1. **Base Case**: Return 0 if $n = 0$ and 1 if $n = 1$.
194 | 2. **Function Call**: Recur on the sum of the $n-1$ and $n-2$ elements.
195 |
196 | #### Python Code
197 |
198 | Here is the Python code:
199 |
200 | ```python
201 | def fibonacci_recursive(n):
202 | if n <= 1:
203 | return n
204 | return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
205 | ```
206 |
207 | #### Complexity Analysis
208 |
209 | - **Time Complexity**: $O(2^n)$ - As each call branches into two more calls (with the exception of the base case), the number of function calls grows exponentially with $n$, resulting in this time complexity.
210 | - **Space Complexity**: $O(n)$ - The depth of the recursion stack can go up to $n$ due to the $n-1$ and $n-2$ calls.
211 |
212 | ### Memoization for Improved Efficiency
213 |
214 | Using **memoization** allows for a noticeable performance boost.
215 |
216 | #### Algorithm
217 |
218 | 1. Initialize a cache, `fib_cache`, with default values of -1.
219 | 2. **Base Case**: If the $n$th value is already calculated (i.e., `fib_cache[n] != -1`), return that value. Otherwise, calculate the $n$th value using recursion.
220 | 3. **Cache the Result**: Once the $n$th value is determined, store it in `fib_cache` before returning.
221 |
222 | #### Python Code
223 |
224 | Here is the Python code:
225 |
226 | ```python
227 | def fibonacci_memo(n, fib_cache={0: 0, 1: 1}):
228 | if n not in fib_cache:
229 | fib_cache[n] = fibonacci_memo(n-1, fib_cache) + fibonacci_memo(n-2, fib_cache)
230 | return fib_cache[n]
231 | ```
232 |
233 | #### Performance Analysis
234 |
235 | - **Time Complexity**: $O(n)$ - Each $n$ is computed once and then stored in the cache, so subsequent computations are $O(1)$.
236 | - **Space Complexity**: $O(n)$ - The space used by the cache.
237 |
238 | ### Iterative Method for Superior Efficiency
239 |
240 | The **iterative approach** shines in terms of time and space efficiency.
241 |
242 | #### Algorithm
243 |
244 | 1. Initialize `a` and `b` as 0 and 1, respectively.
245 | 2. **Loop**: Update `a` and `b` to the next two Fibonacci numbers, replacing them as necessary to ensure they represent the desired numbers.
246 | 3. **Return**: `a` after the loop exits, since it stores the $n$th Fibonacci number.
247 |
248 | #### Python Code
249 |
250 | Here is the Python code:
251 | ```python
252 | def fibonacci_iterative(n):
253 | a, b = 0, 1
254 | for _ in range(n):
255 | a, b = b, a + b
256 | return a
257 | ```
258 |
259 | #### Performance Analysis
260 |
261 | - **Time Complexity**: $O(n)$ - The function iterates a constant number of times, depending on $n$.
262 | - **Space Complexity**: $O(1)$ - The variables `a` and `b` are updated in place without utilizing any dynamic data structures or recursion stacks.
263 |
264 |
265 | ## 5. Describe the _memoization_ technique as applied to the _Fibonacci sequence_ calculation.
266 |
267 | **Memoization** is a technique that makes dynamic programming faster by storing the results of expensive function calls and reusing them.
268 |
269 | To apply memoization to the **Fibonacci sequence**, a list or dictionary (**array** or **hashmap** in terms of computer science) is used to store the intermediate results, essentially turning the calculation process into a more optimized dynamic programming algorithm.
270 |
271 | ### Code Example: Memoized Fibonacci Calculation
272 |
273 | Here is the Python code:
274 |
275 | ```python
276 | def fibonacci_memo(n, memo={0: 0, 1: 1}):
277 | if n not in memo:
278 | memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
279 | return memo[n]
280 |
281 | # Test
282 | print(fibonacci_memo(10)) # Outputs: 55
283 | ```
284 |
285 |
286 | ## 6. Implement an _iterative solution_ to generate the _Fibonacci sequence_, discussing its _time_ and _space complexity_.
287 |
288 | ### Problem Statement
289 |
290 | The task is to **generate the Fibonacci sequence** using an **iterative** approach, and then analyzing its **time and space complexity**.
291 |
292 | ### Solution
293 |
294 | #### Iterative Algorithm
295 |
296 | 1. Initialize `a = 0` and `b = 1`.
297 | 2. Use a loop to update `a` and `b`. On each iteration:
298 | - Update `a` to the value of `b`.
299 | - Update `b` to the sum of its old value and the old value of `a`.
300 | 3. Repeat the loop 'n-1' times, where 'n' is the desired sequence length.
301 |
302 | #### Visual Representation
303 |
304 | Here's how the first few Fibonacci numbers are computed:
305 |
306 | - Iteration 1: $a = 0, \, b = 1, \, b = 0 + 1 = 1$
307 | - Iteration 2: $a = 1, \, b = 1, \, b = 1 + 1 = 2$
308 | - Iteration 3: $a = 1, \, b = 2, \, b = 2 + 1 = 3$
309 | - Iteration 4: $a = 2, \, b = 3, \, b = 3 + 2 = 5$
310 | - And so on...
311 |
312 | #### Complexity Analysis
313 |
314 | - **Time Complexity**: $O(n)$ — This is more efficient than the recursive approach which is $O(2^n)$.
315 | - **Space Complexity**: $O(1)$ — The space used is constant, regardless of the input 'n'.
316 |
317 | #### Implementation
318 |
319 | Here is the Python code:
320 |
321 | ```python
322 | def fibonacci_iterative(n):
323 | if n <= 0:
324 | return "Invalid input. n must be a positive integer."
325 |
326 | fib_sequence = [0] if n >= 1 else []
327 |
328 | a, b = 0, 1
329 | for _ in range(2, n+1):
330 | fib_sequence.append(b)
331 | a, b = b, a + b
332 |
333 | return fib_sequence
334 |
335 | # Example usage
336 | print(fibonacci_iterative(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
337 | ```
338 |
339 |
340 | ## 7. Explain the concept of _dynamic programming_ as it relates to the _Fibonacci sequence_.
341 |
342 | **Dynamic Programming** is a powerful algorithmic technique that is widely used to optimize **recursive problems**, like computing the Fibonacci sequence, by avoiding redundant computations.
343 |
344 | ### Efficient Fibonacci Calculation
345 |
346 | The naive method of Fibonacci computation is highly inefficient, often taking exponential time. Dynamic Programming offers better time complexity, often linear or even constant, without sacrificing accuracy.
347 |
348 | #### Memoization and Caching
349 |
350 | The most common way of optimizing Fibonacci computations is through **memoization**, where function calls are stored with their results for future reference. In Python, you can employ decorators or dictionaries to achieve this.
351 |
352 | Here is the Python code:
353 |
354 | ```python
355 | def memoize(fib):
356 | cache = {}
357 | def wrapper(n):
358 | if n not in cache:
359 | cache[n] = fib(n)
360 | return cache[n]
361 | return wrapper
362 |
363 | @memoize
364 | def fib(n):
365 | if n < 2:
366 | return n
367 | return fib(n-1) + fib(n-2)
368 |
369 | # Test
370 | print(fib(10)) # 55
371 | ```
372 |
373 |
374 | ## 8. Solve the _nth Fibonacci number_ problem using _matrix exponentiation_ and analyze its efficiency.
375 |
376 | ### Problem Statement
377 |
378 | The task is to compute the $n$th Fibonacci number using **matrix exponentiation** and analyze its efficiency.
379 |
380 | ### Solution
381 |
382 | Matrix exponentiation offers an optimal $O(\log n)$ solution for the Fibonacci sequence, in contrast to the traditional recursive method that has a time complexity of $O(2^n)$.
383 |
384 | #### Algorithm Steps
385 |
386 | 1. Represent the **Fibonacci transformation** as $F = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}$.
387 | 2. Utilize **exponentiation by squaring** to efficiently compute $F^n$ for large $n$.
388 | 3. Extract the $n$-th Fibonacci number as the top right element of the resultant matrix.
389 |
390 | #### Complexity Analysis
391 |
392 | - **Time Complexity**: $O(\log n)$ due to the efficiency of exponentiation by squaring.
393 | - **Space Complexity**: $O(\log n)$
394 |
395 | #### Implementation
396 |
397 | Here is the Python code:
398 |
399 | ```python
400 | import numpy as np
401 |
402 | def matrix_power(A, n):
403 | if n == 1:
404 | return A
405 | if n % 2 == 0:
406 | half = matrix_power(A, n // 2)
407 | return np.dot(half, half)
408 | else:
409 | half = matrix_power(A, (n - 1) // 2)
410 | return np.dot(np.dot(half, half), A)
411 |
412 | def fibonacci(n):
413 | if n <= 0:
414 | return 0
415 | F = np.array([[1, 1], [1, 0]])
416 | result = matrix_power(F, n - 1)
417 | return result[0, 0]
418 |
419 | # Example usage
420 | print(fibonacci(6)) # Output: 8
421 | ```
422 |
423 |
424 | ## 9. Can the _nth Fibonacci number_ be found using the _golden ratio_, and if so, how would you implement this method?
425 |
426 | The $n$-th term of the **Fibonacci sequence** can be approximated using the **Golden Ratio** $(\phi \approx 1.61803)$ through Binet's formula:
427 |
428 | $$ F(n) \approx \frac{{\phi^n}}{{\sqrt{5}}} $$
429 |
430 | ### Code Example: Fibonacci with Golden Ratio
431 |
432 | Here is the Python code:
433 |
434 | ```python
435 | import math
436 |
437 | def approximate_fibonacci(n):
438 | golden_ratio = (1 + math.sqrt(5)) / 2
439 | return round(golden_ratio ** n / math.sqrt(5))
440 |
441 | # Test
442 | print(approximate_fibonacci(10)) # Output: 55
443 | ```
444 |
445 |
446 | ## 10. Present an approach to precomputing _Fibonacci numbers_ to answer multiple _nth Fibonacci queries_ efficiently.
447 |
448 | ### Problem Statement
449 |
450 | The objective is to compute $\text{Fib}(n)$, the $n$th Fibonacci number, efficiently for **multiple queries**.
451 |
452 | ### Solution
453 |
454 | A **precomputation** strategy is suitable for scenarios where `Fibonacci` numbers are repeatedly requested over a **fixed range**.
455 |
456 | #### Precomputation Table
457 |
458 | 1. Generate and store Fibonacci numbers from 0 to the highest $n$ using an **array** or **dictionary**. This operation has a time complexity of $O(n)$.
459 | 2. Subsequent queries are answered directly from the precomputed table with a time complexity of $O(1)$.
460 |
461 | #### Complexity Analysis
462 |
463 | - Precomputation: $O(\text{max\_n})$
464 | - Query time: $O(1)$
465 |
466 | #### Realization
467 |
468 | Let's consider Python as our programming language.
469 |
470 | #### Code
471 |
472 | Here is a Python function that precomputes Fibonacci numbers up to a certain limit and then returns the $n$th Fibonacci number based on the precomputed table.
473 |
474 | ```python
475 | def precompute_fibonacci(max_n):
476 | fib = [0, 1]
477 | a, b = 0, 1
478 |
479 | while b < max_n:
480 | a, b = b, a + b
481 | fib.append(b)
482 |
483 | return fib
484 |
485 | def fibonacci(n, fib_table):
486 | return fib_table[n] if n < len(fib_table) else -1
487 |
488 | # Usage
489 | max_n = 100
490 | fib_table = precompute_fibonacci(max_n)
491 | print(fibonacci(10, fib_table)) # 55
492 | ```
493 |
494 |
495 | ## 11. How might the _Fibonacci sequence_ be altered to start with two arbitrary initial values? Provide an algorithm for such a sequence.
496 |
497 | Modifying the **Fibonacci sequence** to start with arbitrary initial values still leads to a unique sequence.
498 |
499 | The iterative approach can handle custom starting values and **compute any term** in the sequence through the specified algorithm.
500 |
501 | ### Algorithm: Custom Fibonacci Sequence
502 |
503 | 1. **Input**: Start values `a` and `b` (with a not equal to b) and target term `n`.
504 | 2. Check if `n` is 1 or 2. If it is, return the corresponding start value.
505 | 3. Otherwise, execute a loop `n-2` times and update the start values.
506 | 4. Compute the `n`-th term once the loop concludes.
507 |
508 | ### Code Example: Custom Fibonacci Sequence
509 |
510 | Here is the Python code:
511 |
512 | ```python
513 | def custom_fibonacci(a, b, n):
514 | if n == 1:
515 | return a
516 | elif n == 2:
517 | return b
518 |
519 | for _ in range(n-2):
520 | a, b = b, a+b
521 | return b
522 |
523 | # Example with start values 3 and 4 for the 6th term
524 | result = custom_fibonacci(3, 4, 6) # Output: 10
525 | ```
526 |
527 |
528 | ## 12. Explain an algorithm to compute the _sum of the first n Fibonacci numbers_ without generating the entire sequence.
529 |
530 | The **Fibonacci sequence** is a classic mathematical series defined by the following:
531 |
532 | $$
533 | F(n) =
534 | \begin{cases}
535 | 0 & \text{if } n = 0 \\
536 | 1 & \text{if } n = 1 \\
537 | F(n-1) + F(n-2) & \text{if } n > 1
538 | \end{cases}
539 | $$
540 |
541 | ### Direct Formulas for Sum and Generalization
542 |
543 | 1. **Sum of First n Numbers**: The sum of the first $n$ Fibonacci numbers is equal to $F(n+2) - 1$.
544 |
545 | This can be computed using a simple, **iterative function**:
546 |
547 | $$ \text{Sum}(n) = F(n+2) - 1 $$
548 |
549 | 2. **n-th Fibonacci Number**: It can be calculated using **two seed values** $F(0)$ and $F(1)$.
550 |
551 | The general form is:
552 |
553 | $$ F(n) = F(0)A + F(1)B $$
554 |
555 | **Matrix Representation**:
556 | $$
557 | \begin{bmatrix}
558 | F(n) \\
559 | F(n-1) \\
560 | \end{bmatrix}
561 | =
562 | \begin{bmatrix}
563 | 1 & 1 \\
564 | 1 & 0 \\
565 | \end{bmatrix}^{(n-1)}
566 | \begin{bmatrix}
567 | F(1) \\
568 | F(0) \\
569 | \end{bmatrix}
570 | $$
571 |
572 | Where:
573 | - $A$ and $B$ vary based on the initial seed values.
574 | - The matrix is multiplied by itself $(n-1)$ times.
575 |
576 | ### Code Example: Sum of First $n$ Fibonacci Numbers
577 |
578 | Here is the Python code:
579 |
580 | ```python
581 | def fibonacci_sum(n):
582 | fib_curr, fib_next, fib_sum = 0, 1, 0
583 |
584 | for _ in range(n):
585 | fib_sum += fib_curr
586 | fib_curr, fib_next = fib_next, fib_curr + fib_next
587 |
588 | return fib_sum
589 | ```
590 |
591 | The time complexity is $O(n)$, which is significantly better than $O(n\log n)$ when computing the $n$-th Fibonacci number using matrix exponentiation.
592 |
593 |
594 | ## 13. Define the _Lucas sequence_ and detail how a program can generate it.
595 |
596 | The **Lucas Sequence**, a variant of the Fibonacci sequence, starts with 2 and 1, rather than 0 and 1, and follows the same recursive structure as the classic sequence:
597 |
598 | $$
599 | \text{Lucas}(n) = \begin{cases}
600 | 2, & \text{if } n = 0, \\
601 | 1, & \text{if } n = 1, \\
602 | \text{Lucas}(n-1) + \text{Lucas}(n-2), & \text{otherwise}.
603 | \end{cases}
604 | $$
605 |
606 | ### Advantages of the Lucas Sequence
607 |
608 | Compared to the Fibonacci sequence, the Lucas sequence offers:
609 |
610 | - **Simpler Recurrence Relation**: The Lucas sequence uses only addition for its recursive relation, which can be computationally more efficient than Fibonacci's addition and subtraction.
611 |
612 | - **Alternate Closed-Form Expression**: While the closed-form formula for the $n$th term of the Fibonacci sequence involves radicals, the Lucas sequence provides an alternate expression that can be easier to work with.
613 |
614 |
615 | ## 14. How can the _Fibonacci sequence_ be used to solve the _tiling problem_, where you need to cover a _2xn rectangle_ with _2x1 tiles_?
616 |
617 | The **Fibonacci sequence** is closely related to the problem of covering a 2xN rectangle with 2x1 tiles, often referred to as the "tiling problem". It in fact offers a direct solution to this problem.
618 |
619 | ### Relationship Between Tiling and Fibonacci Sequence
620 |
621 | Covering a 2xN rectangle $R_{1}$ with 2x1 tiles can be understood in terms of the number of ways to cover the last column, whether with a single vertical tile or two horizontal tiles:
622 |
623 | $$
624 | W_{1}(2xN) = W(2x(N-1)) + W(2x(N-2))
625 | $$
626 |
627 | This is a recursive relationship similar to the one used to define the Fibonacci numbers, making it clear that there is a connection between the two.
628 |
629 | ### Code Example: Tiling a 2xN Rectangle
630 |
631 | Here is the Python code:
632 |
633 | ```python
634 | def tiling_ways(n):
635 | a, b = 1, 1
636 | for _ in range(n):
637 | a, b = b, a + b
638 | return a
639 |
640 | n = 5
641 | ways_to_tile = tiling_ways(n)
642 | print(f'Number of ways to tile a 2x{n} rectangle: {ways_to_tile}')
643 | ```
644 |
645 | In this example, `a, b = b, a + b` is a compact way to **update** `a` and `b`. It relies on the fact that the right-hand side of the assignment is _evaluated first_ before being assigned to the left-hand side.
646 |
647 | This approach has a **time complexity** of $O(N)$ and a **space complexity** of $O(1)$ since it only requires two variables.
648 |
649 |
650 | ## 15. How to calculate large _Fibonacci numbers_ without encountering _integer overflow_ issues?
651 |
652 | **Fibonacci numbers** grow at a rapid rate, which can lead to **integer overflow**. Numerous strategies exist to circumvent this issue.
653 |
654 | ### Various Techniques to Handle Overflow
655 |
656 | 1. **Using a Data Type with Larger Capacity**:
657 | The `long long int` data type in C/C++ provides up to 19 digits of precision, thus accommodating Fibonacci numbers up to $F(92)$.
658 |
659 | 2. **Using Built-in Arbitrary Precision Libraries**:
660 | Certain programming languages such as Python and Ruby come with **arbitrary-precision** arithmetic support, making them suited for such computations.
661 |
662 | 3. **Implementing Custom Arithmetic**:
663 | Libraries like GMP (GNU Multiple Precision Arithmetic Library) and `bigInt` in Java enable the handling of arbitrary-precision operations. Additionally, rolling out a custom arithmetic procedure through **arrays, linked lists, or strings** is viable.
664 |
665 | ### Code Example: Using `long long int` for Larger Capacity
666 |
667 | Here is the C++ code:
668 |
669 | ```cpp
670 | #include
671 | #include
672 | using namespace std;
673 |
674 | long long int fibonacci(int n) {
675 | if (n <= 1) return n;
676 |
677 | long long int a = 0, b = 1, c;
678 | for (int i = 2; i <= n; ++i) {
679 | c = a + b;
680 | a = b;
681 | b = c;
682 | }
683 | return b;
684 | }
685 |
686 | int main() {
687 | int n = 100;
688 | cout << "Fibonacci number at position " << n << " is: "
689 | << fibonacci(n) << endl;
690 | return 0;
691 | }
692 | ```
693 |
694 |
695 | #### Explore all 35 answers here 👉 [Devinterview.io - Fibonacci Sequence](https://devinterview.io/questions/data-structures-and-algorithms/fibonacci-sequence-interview-questions)
696 |
697 |
698 |
699 |
700 |
701 |
702 |
703 |
704 |
--------------------------------------------------------------------------------