Skip to content
Decoder

Odd Even Linked List

Medium

Problem

You get the head of a linked list. Regroup it so that all nodes at odd positions (1st, 3rd, 5th, ...) come first, followed by all nodes at even positions (2nd, 4th, ...). Positions are about where a node sits, not its value. Keep the relative order inside each group, and do it in O(n) time with O(1) extra space.

Example 1

Input
1
Output
2 -> 3 -> 4 -> 5 → 1 -> 3 -> 5 -> 2 -> 4

Example 2

Input
2
Output
1 -> 3 -> 5 -> 6 -> 4 -> 7 → 2 -> 3 -> 6 -> 7 -> 1 -> 5 -> 4

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^6 <= Node.val <= 10^6

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.