702881. Fascinating Number
Here is a detailed markdown blog post for the GeeksforGeeks problem:
Fascinating Number
702881
Summary
The fascinating number problem involves identifying a specific pattern in an array of integers. The given array contains a sequence of numbers where each number is either equal to its previous number plus one or minus one. The goal is to find the first index at which this pattern breaks.
Detailed Explanation
Problem Description
Given an array arr of size n, we need to find the first index i such that arr[i] does not satisfy the condition: either arr[i-1] + 1 == arr[i] or arr[i-1] - 1 == arr[i]. In other words, we are looking for the first index where the difference between two consecutive elements is not equal to 1.
Algorithmic Approach
To solve this problem, we can use a simple iteration over the array. We start by initializing an index i to 0 and a variable prev to the first element of the array (arr[0]). Then, we iterate through the array starting from the second element (index 1). For each element, we check if it satisfies the condition: either it's equal to the previous element plus one or minus one. If not, we return the current index as the result.
Step-by-Step Breakdown
Here is a step-by-step breakdown of the solution:
- Initialize
ito 0 andprevtoarr[0]. - Iterate through the array starting from index 1.
- For each element at index
j, check if it satisfies the condition: eitherprev + 1 == arr[j]orprev - 1 == arr[j]. - If the condition is not satisfied, return
jas the result. - Otherwise, update
prevto the current element and incrementi.
Time and Space Complexity Analysis
The time complexity of this algorithm is O(n), where n is the size of the input array. This is because we are iterating through the array once.
The space complexity is O(1), as we only use a constant amount of space to store the variables i and prev.
Optimized Solutions
Java
public int fascinatingNumber(int[] arr) {
int i = 0;
int prev = arr[0];
for (int j = 1; j < arr.length; j++) {
if (!(prev + 1 == arr[j] || prev - 1 == arr[j])) {
return j;
}
prev = arr[j];
i++;
}
return -1; // or some other default value
}