702921. Fibonacci in the array

Basic

Fibonacci in the Array

Summary

The problem involves finding the index at which the Fibonacci sequence appears in a given array. The Fibonacci sequence is defined as the series of numbers where a number is the sum of the two preceding ones, usually starting with 0 and 1. This problem requires understanding of arrays and Fibonacci series.

Detailed Explanation

Given an integer array arr, we need to find the first index at which the Fibonacci sequence appears in the array. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers (0, 1, 1, 2, 3, 5, 8, ...).

Here's a step-by-step approach to solve this problem:

  1. Initialize two variables prev and curr with values 0 and 1 respectively.
  2. Iterate through the array from index 2 (since the first two elements are 0 and 1).
  3. For each element at index i, check if it's equal to prev + curr. If true, it means the Fibonacci sequence has started appearing in the array, so return the current index i.
  4. Update prev and curr by shifting their values one position ahead (i.e., prev = curr and curr = prev + curr).
  5. Continue this process until the end of the array is reached.

Time complexity: O(n), where n is the length of the input array. Space complexity: O(1), since we only use a constant amount of space to store the previous two Fibonacci numbers.

Here's a simple ASCII art representation of the algorithm:

  arr = [0, 1, 1, 2, 3, 5, ...]
  prev = 0
  curr = 1

  i = 2: arr[i] = 1 (not equal to prev + curr)
  i = 3: arr[i] = 2 (not equal to prev + curr)
  i = 4: arr[i] = 3 (not equal to prev + curr)
  i = 5: arr[i] = 5 (equal to prev + curr) -> return i

Optimized Solutions

Java

View on GeeksforGeeks
public int findFibonacciIndex(int[] arr) {
    if (arr.length < 2) return -1;
    int prev = 0, curr = 1;
    for (int i = 2; i < arr.length; i++) {
        if (arr[i] == prev + curr) return i;
        int temp = prev;
        prev = curr;
        curr = temp + curr;
    }
    return -1; // not found
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.