9. Searching in an array where adjacent differ at most k
9. Searching in an array where adjacent differ at most k
Problem link :- click here
package program;
public class Searching__9
{
/*
A step array is an array of integers where each element has a difference
of at most diff with its neighbor.
Given a key 'key', we need to find the index value of key if multiple-element
exists to return the first occurrence of the key.
arr[] = {4, 5, 6, 7, 6} diff = 1 key = 6
output : 2
we will check the first element than we will jump to the index where there
is a chance of finding the element
*/
static int search(int arr[], int n, int diff, int key)
{
int i=0;
while(i < n)
{
if(arr[i] == key)
return i;
int diff1 = Math.abs(arr[i] - key);
i = i + Math.max(1, diff1/diff);
}
return -1;
}
public static void main(String[] args)
{
int arr[] = {20, 40, 50, 70, 70, 60};
int diff = 20;
int key = 50;
int ans = search(arr, key, diff, key);
if(ans == -1)
System.out.println("Not found");
else
System.out.println("Element found at : " + ans);
}
}
Time complexity :- O(n)
Space complexity :- O(1)
Comments
Post a Comment