Odd Even Linked List - Problem

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note: The relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
💡 Note: Group odd indices (1st, 3rd, 5th nodes) first: [1,3,5], then even indices (2nd, 4th nodes): [2,4]. Final result: [1,3,5,2,4]
Example 2 — Even Length
$ Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
💡 Note: Odd positions (1st,3rd,5th,7th): [2,3,6,7], even positions (2nd,4th,6th): [1,5,4]. Result: [2,3,6,7,1,5,4]
Example 3 — Two Nodes
$ Input: head = [1,2]
Output: [1,2]
💡 Note: Only two nodes: 1st node (odd) stays first, 2nd node (even) stays second. Order unchanged.

Constraints

  • The number of nodes in the linked list is in the range [0, 104]
  • -106 ≤ Node.val ≤ 106

Visualization

Tap to expand
Odd Even Linked List: Group by Position IndexInput: [1,2,3,4,5]12345pos 1pos 2pos 3pos 4pos 5↓ Group by Position ↓Odd positions first:1 → 3 → 5Then even positions:2 → 4Output: [1,3,5,2,4]13524
Understanding the Visualization
1
Input
Original linked list [1,2,3,4,5]
2
Group by Position
Separate odd positions (1,3,5) and even positions (2,4)
3
Output
Rearranged list [1,3,5,2,4]
Key Takeaway
🎯 Key Insight: Maintain two separate chains for odd and even positioned nodes, then connect them to achieve O(1) space complexity
Asked in
Facebook 35 Microsoft 28 Amazon 22 Google 18
236.6K Views
Medium Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen