Leetcode 328: Odd Even Linked List

grid47
grid47
Exploring patterns and algorithms
Oct 5, 2024 5 min read

A linked list where odd and even numbered nodes alternate, glowing softly as they form the correct pattern.
Solution to LeetCode 328: Odd Even Linked List Problem

You are given the head of a singly linked list. Your task is to reorder the list such that all nodes at odd indices are grouped together followed by all nodes at even indices. The first node is considered to have an odd index, the second node is considered to have an even index, and so on. The relative order inside the odd and even groups should remain unchanged.
Problem
Approach
Steps
Complexity
Input: You are given the head of a singly linked list.
Example: head = [1, 2, 3, 4, 5]
Constraints:
• The number of nodes in the linked list is between 0 and 10^4.
• Each node's value is between -10^6 and 10^6.
Output: Return the reordered linked list where all odd-indexed nodes appear first, followed by the even-indexed nodes, while maintaining the relative order within each group.
Example: [1, 3, 5, 2, 4]
Constraints:
• The solution must operate in O(n) time complexity and use O(1) extra space.
Goal: To reorder the linked list such that all odd-indexed nodes come first, followed by the even-indexed nodes, while maintaining the relative order within both groups.
Steps:
• Initialize two pointers, one for odd-indexed nodes and one for even-indexed nodes.
• Traverse the list, separating the nodes into two lists: one for odd indices and one for even indices.
• Connect the last node of the odd list to the head of the even list.
Goal: The solution must work efficiently for large inputs with O(n) time complexity and O(1) space complexity.
Steps:
• The linked list can have up to 10^4 nodes.
• Node values can be as large as 10^6 or as small as -10^6.
Assumptions:
• The input linked list always has a valid solution.
Input: head = [1, 2, 3, 4, 5]
Explanation: The list groups nodes with odd indices first (1, 3, 5), followed by the nodes with even indices (2, 4).

Input: head = [5, 10, 15, 20, 25, 30]
Explanation: The list groups nodes with odd indices first (5, 15, 25), followed by the nodes with even indices (10, 20, 30).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus