Magic Index
A magic index in an array A[0... n-1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.
input = {-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13};
output = 7; // as the index in position 7, is 7.
Link here to the repo to solve the problem
👉👌 Tips
Start with a brute force algorithm.
Your brute force algorithm probably ran in O(N) time. If you're trying to beat that runtime, what runtime do you think you will get to? What sorts of algorithms have that runtime?
Can you solve the problem in O(log N)?
Binary Search has a runtime of O(Log N)
Given a specific index and value, can you identify if the magic index would be before or after it?
👊 Brute Force Solution
This algorithm is really easy to solve in a O(N) fashion, no shame in starting here, but we can do much better.
int iterativeSolution(int[] n) {
for (int i = 0; i < n.length; i++) {
if (n[i] == i) return i;
}
return -1;
}
👊 Better Solution
If we want to solve this problem in Log(N), we need to implement something similar to a binary search. This is plausible, as we know the array is sorted from smaller to bigger.
First we need to get the middle value of the array, if this value is bigger than its index, that means that the value we are after must be in the right. Same applies for the opposite direction.
Then we can recursively calculate with the other half of the array, all we need is the start, and the ending indexes.
Take the array from the example:
int[] numbers = new int[]{-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13};
// start = 0
// end = 10
// middleIndex = 5
// value = 3
// we need to move right, as the index is bigger
// start = 6
// end = 10
// middleIndex = 8
// value = 9
// we need to move left, as the index is smaller
// start = 6
// end = 9
// middleIndex = 7
// value = 7
// We've found the magic index! :)
The code would look like this:
public int recursively(int[] n) {
return recursively(n, 0, n.length -1);
}
private int recursively(int[] array, int start, int end) {
if (end < start) return -1;
int mid = (start + end) / 2;
if (mid == array[mid]) return mid;
else if (array[mid] > mid) {
return recursively(array, start, mid - 1); // we need to go left
}
else return recursively(array, mid + 1, end); // we need to go right
}
Question borrowed from “Cracking the coding interview”