Challenge: Search Insert Position
Let's write a function to find the appropriate position to insert a new element in a sorted array.
We'll cover the following
Problem statement
Given a sorted array and a target value, return the index where the target value would be if it were inserted in order. If the target index is already present in the array, return the index of where it is found. You may assume that no duplicates are in the array.
Input
A sorted array, and a target value
Output
The index at which the array should be inserted OR the index at which it is already present
Sample input
int arr[] = {1,3,5,6};
int target = 5;
Sample output
2
Coding exercise
Take a close look and design a step-by-step algorithm before jumping to implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the code tab. Good Luck!
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.