Challenge: Search Position

Solve the challenge of finding an appropriate position to insert a new element in a sorted array.

Problem statement

Given a sorted array and a target value, return the index of the target value if the value is present in the array. If the value is not present, return the index at which the value should be inserted.

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

arr = { 1, 3, 5, 6 };
value = 5;

Sample output

result = 2;

Coding exercise

First, take a close look at this problem and design a step-by-step algorithm before jumping to the 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 solution section. Good luck!

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.