Magic Index

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
CodingNinjas
author
2y
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 a...read more
CodingNinjas
author
2y
Binary Search Approach(This Approach will only work when the given input contains distinct elements)
  • In this approach, we will be using binary search as the given array is always sorted.
  • We can apply bi...read more
CodingNinjas
author
2y
Modified Binary Search
  • When the given array has duplicate elements in it, then the normal binary search approach will fail, therefore we need a modified solution.
  • In this approach, we will again be usin...read more
Add answer anonymously...
Info Edge Front end Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter