Magic Index

Easy
0/40
Average time to solve is 20m
profile
Contributed by
212 upvotes
Asked in companies
MicrosoftFacebookAdobe

Problem statement

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

Note :
1. A magic index in an array A[0 ... N - 1] is defined to be an index i such that A[i] = i.
2. The elements in the array can be negative.
3. The elements in the array can be repeated multiple times.
4. There can be more than one magic index in an array.
Detailed explanation ( Input/output format, Notes, Images )
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, return any of them.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
-10^9 <= A[i] <= 10^9

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

Check each index one by one.

Approaches (3)
Brute Force Approach
  • In this brute force approach, we will check each element one by one and try to find if there is any magic index in the given array or not.
  • In this approach, we will initialize our answer variable (say, ans) with ans = -1.
  • Then we will iterate in the array one by one (say, loop variable i) from the beginning and check if there is any magic index in our array or not.
  • If we find any index in the array such that A[i] = i, then we will assign this current index i to our answer variable ans(i.e. ans = i ) and break this loop as we have found a magic index and our task is complete.
  • Finally we will print this ans variable as the answer.,
Time Complexity

O(N), where N is the number of elements in the array.

 

Since we iterate through the given array only once hence the time complexity will be O(N).

Space Complexity

O(1). 

 

Since we are using constant extra space to store our answer, so the space complexity is O(1).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Magic Index
Full screen
Console