Challenge: Search Position

Let's write a function to find the appropriate position to insert a new element in a sorted list.

Problem statement

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

You may assume that no duplicates are in the list.

Input

A sorted list and a target value

Output

The index at which the list should be inserted OR the index at which it is already present

Sample input

  lst = [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.