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
• Achieve
Example:
The odd-positioned nodes (1,3,5) come first, then even-positioned nodes (2,4).
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 complexityExample:
1→2→3→4→5 becomes 1→3→5→2→4The 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code