Arrays : Finding the Element in array where next element is +1, +0 or -1
Problem Statement
You are given an array where each element follows the rule that given any index, the number at that index will either be
- +1 of the number at that index.
- +0 of the number at that index.
- -1 of the number at that index.
Suppose the array is
Sample Input
arr = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4};
search = 5
Sample Output
6 (First occurrence of search )
Sample Input
arr = {1,2,1,2,1,2,1,2,1,2};
search = 5
Sample Output
1 ( Element is not found in the array)
Algorithm
- Star iterating from start of the array.
- Check if the value at the index is same as the search value
- if yes, then return the index
- if no, then increment the index counter by modulus of difference of value to search and value at index
- return -1 if value to search does not exist in the array.
Java Program
- package com.ekiras.arrays;
- public class SearchElement {
- private static final int[] arr = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4};
- public static void main(String args[]){
- System.out.println("elemet found at :: " + find(5) + "th index");
- }
- public static int find(int search){
- int cntr=0;
- while(cntr<arr.length){
- if(arr[cntr]==search)
- return cntr;
- else{
- cntr += Math.abs(search - arr[cntr]);
- }
- }
- return -1;
- }
- }
No comments: