Skip to problem
←

Even-Valued Nodes Before Odd-Valued Nodes

Medium 0 attempts

Rearrange a nonempty singly linked list so that all nodes with even values appear before all nodes with odd values. Preserve the original relative order within each group.

Classify by node value, not by position. Zero is even, and negative integers follow the same parity rule. Rewire the original nodes without changing their values or creating replacements, then return the new head.

For [17, 15, 8, 12, 10, 5, 4], return [8, 12, 10, 4, 17, 15, 5]. The even group is not sorted; its original order remains intact. If every node belongs to one group, keep the entire list in its original order.

Your function receives nodes with val and next properties. Examples display lists as value arrays.

Function contract

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

Output: Return the head with all original even-valued nodes followed by all original odd-valued nodes, preserving relative order within each group.

Example 1

Input
head = [17,15,8,12,10,5,4]
Output
[8,12,10,4,17,15,5]

Example 2

Input
head = [1,3]
Output
[1,3]
Constraints
  • 1 <= N <= 10^4
  • Node values are safe JavaScript integers; zero, negative values, and duplicates are allowed.
Topics

Build Stable Even and Odd Chains

Maintain separate dummy heads and tails for even and odd values. Traverse the original nodes once, appending each to its matching chain. Appending in input order preserves relative order inside both groups.

Set the odd tail's next link to null before joining the chains: its old link may still point to an even node and would otherwise create a cycle. Connect the even tail to the odd head and return the even dummy's next node.

Dummy heads handle all-even and all-odd lists without special cases. They are temporary helpers; every returned node comes from the original input. Testing remainder against zero correctly handles negative even values too.

javascript
function segregateEvenOdd(head) {
  const even = { next: null },
    odd = { next: null };
  let e = even,
    o = odd,
    curr = head;
  while (curr) {
    if (curr.val % 2 === 0) {
      e.next = curr;
      e = e.next;
    } else {
      o.next = curr;
      o = o.next;
    }
    curr = curr.next;
  }
  o.next = null;
  e.next = odd.next;
  return even.next;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript