InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Odd Even Linked List

medium Original ↗ 00:00

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`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug