Taro Logo

Odd Even Linked List

#222 Most AskedMedium
0 views
Topics:
Linked Lists

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

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How should we handle an empty linked list (i.e., when head is null) or a list with only a single node?
  2. Does 'odd' and 'even' refer to the 1-based index of the nodes in the list, or the actual integer values stored inside the nodes?
  3. Should the reordering be performed in-place by modifying the existing pointers, or are we allowed to allocate a new linked list?
  4. Can I assume the linked list nodes will always contain standard integer values, and what is the expected range of these values?
  5. Is there any specific memory complexity constraint I need to adhere to beyond achieving O(1) extra space?

Brute Force Solution

Approach

Imagine you have a line of people holding hands, where everyone has a numbered position from first to last. The brute force approach involves completely taking the line apart, making separate piles for the people in odd positions and the people in even positions, and then gluing them back together.

Here's how the algorithm would work step-by-step:

  1. Walk down the entire line from start to finish and gently pluck out every person standing in an odd position.
  2. Put all these odd-position people into a brand new, separate row while keeping them in the exact order you found them.
  3. Walk down the original line one more time and pluck out every person standing in an even position.
  4. Put all these even-position people into another separate row, again maintaining their original order.
  5. Take the row of odd-position people and place them all together first.
  6. Attach the entire row of even-position people immediately behind the odd-position group.
  7. Hand the newly combined line back as your final result.

Code Implementation

def odd_even_list(head):
    if not head or not head.next:
        return head

    odd_nodes_list = []
    even_nodes_list = []

    current_node = head
    is_odd_position = True

    while current_node:
        if is_odd_position:
            odd_nodes_list.append(current_node)
        else:
            even_nodes_list.append(current_node)
        current_node = current_node.next
        is_odd_position = not is_odd_position

    # We collect all nodes into separate lists to decouple them from their original interleaved positions
    combined_nodes = odd_nodes_list + even_nodes_list

    for index in range(len(combined_nodes) - 1):
        combined_nodes[index].next = combined_nodes[index + 1]

    # We rebuild the pointer connections so that every node correctly links to its newly assigned successor
    combined_nodes[-1].next = None

    return combined_nodes[0]

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by walking down the line of length n multiple times to separate and rearrange the elements. Specifically, we traverse the entire linked list once to collect and build the odd-position group, and then we traverse it a second time to collect and build the even-position group. Because these two passes happen sequentially rather than nested, the total operations approximate n plus n, which simplifies to O(n).
Space Complexity
O(1) – The plain English explanation describes gathering nodes into separate rows or piles, which translates in an optimized pointer-based implementation to reusing the existing nodes without creating new data structures. We only allocate a constant number of pointer variables to track the heads and current positions of the odd and even groups during traversal. Because these few pointers require a fixed amount of memory regardless of the input size N, the auxiliary space complexity remains constant. Thus, no extra arrays, hash maps, or recursive stacks grow with N, resulting in O(1) auxiliary space.

Optimal Solution

Approach

The optimal approach rearranges the list by separating the items into two distinct groups based on their original positions, keeping their relative order intact. Finally, it connects the end of the first group directly to the beginning of the second group to form a single, seamlessly merged chain.

Here's how the algorithm would work step-by-step:

  1. Imagine you have a long line of people standing one behind the other, and you want to separate them into two groups: those in odd-numbered spots and those in even-numbered spots.
  2. Set aside two separate leaders to keep track of the front of each group so you never lose your place.
  3. Walk down the original line step by step, taking turns to weave the odd-positioned people into one continuous chain and the even-positioned people into another.
  4. As you weave, make sure everyone still faces the same direction they originally did, preserving their relative order within their separate groups.
  5. Once you reach the end of the original line, take the tail end of the odd-positioned group and link it directly to the front of the even-positioned group.
  6. Review your final combined chain to ensure it flows smoothly from all the odd positions straight into all the even positions.

Code Implementation

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def odd_even_list(head_node):
    if not head_node or not head_node.next:
        return head_node

    odd_group_head = head_node

    even_group_head = head_node.next

    current_odd_node = odd_group_head

    current_even_node = even_group_head

    # We track the even head because we need it later to bridge the two groups together.
    even_list_start = even_group_head

    # We traverse while there are even nodes and subsequent nodes to weave together.
    while current_even_node and current_even_node.next:
        current_odd_node.next = current_even_node.next

        current_odd_node = current_odd_node.next

        current_even_node.next = current_odd_node.next

        current_even_node = current_even_node.next

    # We connect the tail of the odd chain directly to the preserved head of the even chain.
    current_odd_node.next = even_list_start

    return odd_group_head

Big(O) Analysis

Time Complexity
O(n) – To rearrange the linked list, we walk down the original line step by step, visiting each of the n nodes exactly once to weave them into odd and even groups. As we traverse the single chain, constant time operations are performed at each node to update our pointers and maintain the relative order. Once the end of the line is reached, we link the tail of the odd group directly to the front of the even group in a single step. Therefore, the total number of operations scales linearly with the input size n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only uses a few pointers and scalar variables to keep track of the odd and even leaders and to traverse the original line step by step. These pointers operate in place by rewiring the existing node connections without allocating any additional data structures or recursion stack frames. As the input size N grows, the amount of extra memory required remains entirely constant. Therefore, the auxiliary space complexity simplifies to O(1).

Edge Cases

Null head or single node linked list
How to Handle:
The algorithm should immediately return the head since no reordering is necessary for lists with zero or one element.
Linked list with exactly two nodes
How to Handle:
The odd pointer stays at the first node, the even pointer stays at the second, and linking is trivial without changes.
Linked list with an odd total number of nodes
How to Handle:
The even pointer will naturally reach the end and become null while the odd pointer handles the final node correctly.
Linked list with an even total number of nodes
How to Handle:
The odd pointer will reach the second-to-last node before the even pointer hits the end, allowing clean termination.
Very long linked lists scaling to maximum constraints
How to Handle:
An iterative two-pointer approach ensures O(1) auxiliary space complexity and O(n) time complexity without stack overflow risks.
Nodes containing negative numbers, zeros, or duplicates
How to Handle:
Since the grouping is purely index-based rather than value-based, node values do not affect the pointer rearrangement logic.
0/257 completed