oneby7

Linked Lists Reversing and rewiring

309. Sort a Linked List of 0s, 1s and 2s

Medium

You are given head, the first node of a singly linked list. Every node holds the value 0, 1 or 2. Rearrange the list so that all the 0s come first, then all the 1s, then all the 2s, and return the head of the rearranged list.

The list keeps its length, and each value appears as many times as it did before. Any of the three values can be missing.

The examples write a list as its values from the head on, so head = [2,0,1] is the list 2 → 0 → 1. The output shows the node you return the same way, as the list from that node on, and shows null as [].

Example 1

head
1201021
output
0011122

Input: head = [1, 2, 0, 1, 0, 2, 1]

Output: [0,0,1,1,1,2,2]

Explanation: The list holds two 0s, three 1s and two 2s. The two 0s come first, then the three 1s, then the two 2s.

Example 2

2020
head
0022
output

Input: head = [2, 0, 2, 0]

Output: [0,0,2,2]

Explanation: There are no 1s, so the two 2s come straight after the two 0s.

Example 3

211
head
112
output

Input: head = [2, 1, 1]

Output: [1,1,2]

Explanation: There are no 0s, so the list now starts at a node holding 1.

Check your understanding

Work out the answer for this input before you write any code.

head = [2, 1, 0, 0, 2, 1]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • Node.val is 0, 1 or 2

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.