Skip to the code
cf.
+25 XP

#189 Insertion Sort a Linked Playlist

medium

A music app stores a playlist as a singly linked list of ListNodes, where each val is a track's length in seconds. The user taps "Shortest first".

Write sortPlaylist(head) that sorts the list ascending by val and returns the new head. Use insertion sort: take nodes one at a time from the original list and insert each into the right place in a growing sorted list. Equal values must keep their original order.

Example 1

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Each node is inserted into its place in the sorted part.

Example 2

Input: head = [180,95,240,95]
Output: [95,95,180,240]

Both 95s move to the front, in their original order.

Constraints

  • 0 <= number of nodes <= 2000
  • 1 <= val <= 10^4

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).