Wednesday, April 20, 2016

Amazon Question: +1 or -1 Array Searching

Given an array, next element is either +1 or -1 of previous element then find any number k ?

    public int getIndex(int element, int[] input) { //element = k
        int size = input.length;
        for(int i=0; i < size;) {

            if(input[i]==element)
                return i;
            i=i+getPositive(element - input[i]);
        }
        return -9999; // element not found
    }
    private int getPositive(int i)    {
        if (i>0) return i;
        return (i * -1);
    }


Example 1:
Input: 4 5 4 5 6 7 8 9 8 9 10 11
k = 8
Output = 6

Example 2:
Input: 11 10 9 8 7 6 5 4 5 6 7 8 9 10 11
k = 4
Output = 7
UA-39217154-2