Insert a Value Into a Sorted List

Medium ⏱ 12 min 54% acceptance ★★★★★ 4.7
Write insert_sorted(items, value) that inserts value into the ascending-sorted list items at the correct position to keep it sorted, and returns the list. Do not call .sort() afterward — find the position and use .insert().

Examples

Example 1
Input
items = [1, 3, 5, 7], value = 4
Output
[1, 3, 4, 5, 7]
Explanation

4 belongs between 3 and 5.

Constraints

  • items is already sorted ascending.
  • 0 <= len(items) <= 10^4

Topics

ListsSearching

Companies

GooglePayPal

Hints

Hint 1

Scan for the first index where items[i] > value, and insert there.

Hint 2

If value is bigger than everything, it belongs at the end.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.