InterviewPrepKit

Home / Coding / Linked List

Odd Even Linked List

medium Original β†—
Solving tips
  • Group by POSITION parity (1st, 3rd, ... then 2nd, 4th, ...), not node value parity; re-read the problem.
  • Unzip in place: keep odd and even tails, save even_head, then repeatedly odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next, and finally odd.next = even_head.
  • Loop condition must be 'even and even.next' (testing only odd.next breaks on even-length lists); O(n) time, O(1) space.
  • Terminate the even chain (even_tail.next = None in the two-dummy variant) or you create a cycle/trailing garbage; two dummy heads are an easier-to-reason alternative at the same complexity.

Problem

Given the head of a singly linked list, regroup its nodes so that all nodes in odd positions (1st, 3rd, 5th, …, counting from 1) come first, followed by all nodes in even positions (2nd, 4th, 6th, …). Within each group the original relative order must be preserved.

Note the grouping is by position in the list, not by whether the node’s value is odd or even.

You must do it in O(1) extra space and O(n) time.

Examples

  • Input: head = [1, 2, 3, 4, 5] β†’ Output: [1, 3, 5, 2, 4] Odd positions hold 1, 3, 5; even positions hold 2, 4.
  • Input: head = [2, 1, 3, 5, 6, 4, 7] β†’ Output: [2, 3, 6, 7, 1, 5, 4] Positions 1,3,5,7 hold 2,3,6,7; positions 2,4,6 hold 1,5,4.
  • Input: head = [7] β†’ Output: [7] A single node is trivially already grouped.

Constraints

  • 0 <= n <= 10^4 where n is the number of nodes.
  • -10^6 <= Node.val <= 10^6.
  • Required: O(1) extra space, O(n) time β€” so no copying nodes into an array in the intended solution.

Think about it first

Hint 1 If space were free, you could walk the list once collecting odd-position nodes in one bucket and even-position nodes in another, then chain the buckets. What would the in-place version of "two buckets" look like?
Hint 2 Keep two tails growing in place: an odd tail and an even tail. Each node you visit belongs to exactly one of them, and the nodes alternate.
Hint 3 Let `odd` start at node 1 and `even` at node 2 (save node 2 as `even_head`). Repeatedly do `odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next` β€” you are unzipping the list into two chains. Finish by pointing the odd tail at `even_head`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.