Sort a linked list of 0s, 1s and 2s Easy 0 attempts
GeeksforGeeks ↗

Sort a linked list of 0s, 1s and 2s

Easy Linked List GeeksforGeeks

Sort a linked list of 0s, 1s, and 2s by changing node data.

Example: 1→2→2→1→2→0→2→2 → 0→1→1→2→2→2→2→2

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

Count and Overwrite

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)

Saved in this browser only. Private to you.

JavaScript