Continue learning
Practice related DSA questions in the same topic.
Sort the sequence by inserting each new item into the already ordered prefix.
Sort the sequence by inserting each new item into the already ordered prefix.
def solve(values, target): a = values.copy() i = 1 while (i < len(a)): key = a[i] j = (i - 1) while ((j >= 0) and (a[j] > key)): a[(j + 1)] = a[j] j = (j - 1) a[(j + 1)] = key i = (i + 1) return aShift a larger item right to make room for 2.
Shift a larger item right to make room for 2.
Insert a new playing card into the ordered hand you already hold.
Save the incoming key before shifting larger entries right.
O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary auxiliary space
Worked example · {"values":[6,2,4,1],"target":0} ⇒ [1,2,4,6]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[2,2],"target":0} ⇒ [2,2]
Overwriting the key before saving it silently duplicates another card.
Why is insertion sort useful on nearly sorted input?