Skip to problem
←

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

Easy 0 attempts

Given a nonempty linked list whose node values are only 0, 1, or 2, overwrite its values so they appear in nondecreasing order: all zeros, then ones, then twos.

Preserve every original node and next link. This version asks you to change values, not rearrange or replace nodes. Do not return a new list.

Function contract

Implement sortList012(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Overwrite values in the existing list nodes. Keep the head, node order, and every next link unchanged. The runner displays the final values; the function return value is ignored.

Example 1

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

Example 2

Input
head = [0]
Output
[0]
Constraints
  • 1 <= N <= 10^3
  • 0 <= Node.val <= 2
Topics

Count and Overwrite

javascript
function sortList012(head) {
  let c = [0,0,0], curr = head;
  while (curr) { c[curr.val]++; curr = curr.next; }
  curr = head;
  for (let v = 0; v <= 2; v++) while (c[v]-- > 0) { curr.val = v; curr = curr.next; }
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript