Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-049

Insert into Sorted Array

Problem

Insert value into an already sorted list, keeping it sorted.

Build the output by copying elements until the first element strictly greater than value, insert value there, then continue copying; append value at the end if no larger element exists. Duplicate values are placed after existing equal ones.

Return the new list without modifying nums.

Hint

Insert right before the first element that is strictly greater than the new value.

Test cases

case 1
in: [[1,3,5],4]
expected: [1,3,4,5]
case 2
in: [[1,1,2],1]
expected: [1,1,1,2]
case 3
in: [[],5]
expected: [5]
case 4
in: [[2,4],0]
expected: [0,2,4]
Starter codePython
def insert_sorted(nums, value):
    # Your code here
    pass

4 test cases · run your code against them in the editor