702921. Fibonacci in the array
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:
- Initialize two variables
prevandcurrwith values 0 and 1 respectively. - Iterate through the array from index 2 (since the first two elements are 0 and 1).
- For each element at index
i, check if it's equal toprev + curr. If true, it means the Fibonacci sequence has started appearing in the array, so return the current indexi. - Update
prevandcurrby shifting their values one position ahead (i.e.,prev = currandcurr = prev + curr). - 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
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
}