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.
Be the first one to answer
Add answer anonymously...
Top Uber SDE-2 interview questions & answers
Popular interview questions of SDE-2
Stay ahead in your career. Get AmbitionBox app
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