Magic Index

Difficulty: MEDIUM
Contributed By
Arshit Babariya
Avg. time to solve
20 min
Success Rate

Problem Statement
Suggest Edit

You are given a sorted array A consisting of N integers. Your task is to find the magic index in the given array.

Note :
A magic index in an array A[0 ... N - 1] is defined to be an index i such that A[i] = i.

The elements in the array can be negative.

The elements in the array can be repeated multiple times.

There can be more than one magic index in an array.
Input Format :
The first line of the input contains an integer T denoting the number of test cases.

The first line of each test case contains one integer N, as described in the problem statement.

The second line of each test case contains N space-separated integers, representing the elements of the array.
Output Format :
For each test case print in a new line, one integer representing the magic index of the given array or -1 if there does not exist any magic index for the given array.

In case there is more than one magic index, print any of them.
Note :
You will print the magic indices, then the runner will check whether it is a magic number or not. If your output magic numbers are correct, the runner will print "Correct", else "Incorrect".
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
-10^9 <= A[i] <= 10^9

Time Limit: 1sec
Sample Input 1 :
-5 -1 2 1 9
Sample Output 1 :
Explanation For Sample Input 1 :
The output is 2 because A[2] = 2 and hence 2 is the magic index.
Sample Input 2 :
2 3 4 5 6
-1 -1 -1 4 4 4
Sample Output 2 :
Reset Code
Full screen