Odd Even Linked List - Problem
Odd Even Linked List

You're given the head of a singly linked list and need to rearrange it in a specific pattern. Your task is to group all nodes at odd positions (1st, 3rd, 5th, etc.) together, followed by all nodes at even positions (2nd, 4th, 6th, etc.).

Important: We're talking about position indices, not the values stored in the nodes. The first node is at position 1 (odd), the second at position 2 (even), and so on.

Requirements:
• Maintain the relative order within each group
• Solve in O(1) extra space
• Achieve O(n) time complexity

Example: 1→2→3→4→5 becomes 1→3→5→2→4
The odd-positioned nodes (1,3,5) come first, then even-positioned nodes (2,4).

Input & Output

example_1.py — Basic Example
$ Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
💡 Note: The odd-positioned nodes (1st, 3rd, 5th) are grouped first: 1→3→5, then the even-positioned nodes (2nd, 4th): 2→4. Final result: 1→3→5→2→4
example_2.py — Even Length
$ Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
💡 Note: Odd positions: 2(1st)→3(3rd)→6(5th)→7(7th), Even positions: 1(2nd)→5(4th)→4(6th). Result: 2→3→6→7→1→5→4
example_3.py — Single Node
$ Input: head = [1]
Output: [1]
💡 Note: A single node is already properly arranged since there are no even-positioned nodes to separate.

Constraints

  • The number of nodes in the linked list is in the range [0, 104]
  • -106 ≤ Node.val ≤ 106
  • Follow up: Solve in O(1) extra space complexity and O(n) time complexity

Visualization

Tap to expand
Odd-Even Linked List VisualizationOriginal List:1pos 12pos 23pos 34pos 45pos 5Separation Process:Odd Chain:135Even Chain:24Final Result:135Link24Algorithm Steps1. Initialize two pointers:• odd = head (position 1)• even = head.next (position 2)2. Build separate chains:• Connect odd nodes: 1→3→5• Connect even nodes: 2→43. Link chains together:• odd_end.next = even_headComplexity AnalysisTime: O(n) - Single pass through listSpace: O(1) - Only using pointers
Understanding the Visualization
1
Identify Pattern
Recognize that we need to separate nodes based on their position (odd vs even)
2
Use Two Pointers
Initialize odd pointer at position 1, even pointer at position 2
3
Build Separate Chains
Connect all odd-positioned nodes together, all even-positioned nodes together
4
Link the Chains
Connect the end of odd chain to the beginning of even chain
Key Takeaway
🎯 Key Insight: By using two pointers to build separate chains for odd and even positioned nodes, we can rearrange the linked list in-place with optimal time and space complexity.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 22
89.2K Views
High Frequency
~15 min Avg. Time
1.8K 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