Copied to Clipboard
Search insert position of K in a sorted array
Easy Accuracy: 49.94% Submissions: 13156 Points: 2

Given a sorted array Arr[](0-index based) consisting of distinct integers and an integer k, the task is to find the index of k, if it’s present in the array Arr[]. Otherwise, find the index where k must be inserted to keep the array sorted.

Example 1:

N = 4
Arr = {1 , 3, 5, 6}
k = 5
Output: 2
Explaination: Since 5 is found at index 2 
as arr[2] = 5, the output is 2.

Example 2:

N = 4
Arr = {1, 3, 5, 6}
k = 2
Output: 1
Explaination: Since 2 is not present in 
the array but can be inserted at index 1 
to make the array sorted.

Your Task:
You don't need to read input or print anything. Your task is to complete the function searchInsertK() which takes the array Arr[] and its size N and as input parameters and returns the index.

Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)

1 ≤ N ≤ 104
-103 ≤ Arr[i] ≤ 103
-103 ≤ k ≤ 103

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.

to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.

Search insert position of K in a sorted array

Output Window