Efficient search in an array where difference between adjacent is 1

Given an array of n integers. Each array element is obtained by adding either +1 or -1 to previous element i.e absolute difference between any two consecutive elements is 1. The task is to search an element index with the minimum number of comparison (less than simple element by element search). If the element is present multiple time, then print the smallest index. If the element is not present print -1.

Examples:

Input : arr[] = {5, 4, 5, 6, 5, 4, 3, 2} 
        x = 4.
Output : 1
The first occurrence of element x is at 
index 1.

Input : arr[] = { 5, 4, 5, 6, 4, 3, 2, 3 } 
        x = 9.
Output : -1
Element x is not present in arr[]

Let element to be search is x. At any index i, if arr[i] != x, the possibility of x to be present is at location i + abs(arr[i] – a), since each element is obtained by adding either +1 or -1 to the previous element. There is no possibility of having el between i and i + abs(arr[i] – a). So directly jump to i + abs(arr[i] – a), if arr[i] != x.

Algorithm to solve the problem:
1. Start from index = 0.
2. Compare arr[index] and x.
   a) If both are equal, return index.
   b) If not, set index = index + abs(arr[index] - x).
3. Repeat step 2.

Below is C++ implementation of this approach:

// C++ program to search an element in an array
// where each element is obtained by adding
// either +1 or -1 to prefious element.
#include<bits/stdc++.h>
using namespace std;

// Return the index of the element to be searched.
int search(int arr[], int n, int x)
{
    // Searching x in arr[0..n-1]
    int i = 0;
    while (i <= n-1)
    {
        // Checking if element is found.
        if (arr[i] == x)
            return i;

        // Else jumping to abs(arr[i]-x).
        i += abs(arr[i]-x);
    }

    return -1;
}

// Driven Program
int main()
{
    int arr[] =  {5, 4, 5, 6, 5, 4, 3, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 4;

    cout << search(arr, n, x) << endl;

    return 0;
}

Output:

1

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.