Skip to content

Insertion Sort Shift Count

Easy#insertion-sort#stable-sort~15 min

The mission

Problem

Insertion sort places each new value by sliding every larger value in the sorted part one slot to the right. Given a list of numbers, return how many single-slot slides insertion sort performs while sorting it into ascending order. Equal values never slide past each other, and the input list must not be modified.

Examples

Input:  nums = [3, 1, 2]
Output: 2
Why:    placing 1 slides 3 once, then placing 2 slides 3 once more
Input:  nums = [5, 4, 3, 2, 1]
Output: 10
Why:    each new value slides every value already placed
Input:  nums = [2, 2, 2]
Output: 0
Why:    edge case, equal values stay where they are

Hints

0 / 3

Target time
O(n²)
Target space
O(n)

Stuck on the idea rather than the code? Insertion Sort covers it.

Python 3Ctrl+Enter runs
Custom test case