Best Insert Position for a Target in a Sorted Array
You are provided with a sorted array A
of length N
consisting of distinct integers and a target integer M
. Your task is to determine the position where M
would be inserted into the array A
to maintain the sorted order. If M
is already present in the array, return its current index. Note that 0-based indexing is used.
Input:
The first line includes a single integer T
, representing the number of test cases. Each test case consists of: - A line with two space-separated integers, N
and M
, indicating the array's length and the target integer. - A line with N
space-separated integers representing the array A
.
Output:
Output a single integer for each test case on a new line, representing the position M
would occupy in a sorted version of the array
Example:
Input:
N = 4, M = 6
A = [1, 2, 4, 7]
Output:
3
Explanation:
Inserting 6 into the array gives[1, 2, 4, 6, 7]
. The position of 6 is 3.
Constraints:
1 ≤ T ≤ 10
0 ≤ N ≤ 10^5
1 ≤ M ≤ 10^9
1 ≤ A[i] ≤ 10^9
- The given array
A
contains distinct integers. - Time Limit: 1 second
Note:
There is no need for explicit output statements in your code. Implement the function to return results for test cases.
Additional Challenge:
Aim to achieve the solution in O(log N) time complexity.

AnswerBot
4mo
Find the best insert position for a target in a sorted array to maintain order.
Use binary search to find the correct position for the target integer in the sorted array.
If the target is already presen...read more
Help your peers!
Add answer anonymously...
Uber SDE-2 interview questions & answers
A SDE-2 was asked Q. Rat In a Maze Problem Statement Given a N * N maze with a rat placed at position...read more
A SDE-2 was asked Q. Smallest Subarray with K Distinct Elements Problem Given an array A consisting o...read more
A SDE-2 was asked Q. House Robber Problem Statement Mr. X is a professional robber with a plan to rob...read more
Popular interview questions of SDE-2
A SDE-2 was asked Q1. Rat In a Maze Problem Statement Given a N * N maze with a rat placed at position...read more
A SDE-2 was asked Q2. Smallest Subarray with K Distinct Elements Problem Given an array A consisting o...read more
A SDE-2 was asked Q3. House Robber Problem Statement Mr. X is a professional robber with a plan to rob...read more
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

