Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created February 8, 2023 13:41
Show Gist options
  • Save ravichandrae/3e8c4dd62aeba5ca71ca2ac5cf32042d to your computer and use it in GitHub Desktop.
Save ravichandrae/3e8c4dd62aeba5ca71ca2ac5cf32042d to your computer and use it in GitHub Desktop.
Given a sorted array of unique positive and negative numbers, find if there is an index i such that A[i] = i
public class IndexElementArray {
public static void main(String[] args) {
System.out.println(indexElement(new int[] {-5, -3, 0, 3, 5})); //Expect True
System.out.println(indexElement(new int[] {-5, -3, 0, 1, 2})); //Expect false
System.out.println(indexElement(new int[] {0, 2, 3, 4, 5})); //Expect True
System.out.println(indexElement(new int[] {-1, 0, 1, 2, 4})); //Expect True
System.out.println(indexElement(new int[] {-10, 10, 20, 30, 40})); //Expect false
}
private static boolean indexElement(int []arr) {
if (arr == null || arr.length == 0) {
return false;
}
int low = 0, high = arr.length - 1;
int mid = 0;
while(low <= high) {
mid = (low + high) / 2;
if(arr[mid] == mid) {
return true;
} else if(arr[mid] < mid) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment