Reorder List in Python and Java
In this tutorial, we will learn LeetCode #143: Reorder List in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Reorder List Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use middle reverse merge because it gives a clean and optimized solution.
Example input: head = [1, 2, 3, 4, 5] Expected result: Output: [1, 5, 2, 4, 3] Explanation: Reorder first, last, second, second last.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: head = [1, 2, 3, 4, 5] Approach: middle reverse merge We update variables step by step until we reach: Output: [1, 5, 2, 4, 3]
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why middle reverse merge is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. head = [1, 2, 3, 4, 5] We will solve it using middle reverse merge. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: [1, 5, 2, 4, 3] Why? Reorder first, last, second, second last.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: [1, 5, 2, 4, 3]
Example 1
Input: head = [1, 2, 3, 4, 5] Output: Output: [1, 5, 2, 4, 3] Explanation: Reorder first, last, second, second last.
Example 2
Input: head = [2, 4, 6, 8] Output: [2, 8, 4, 6] Explanation: The list is reordered from first, last, second, second-last.
Python Code
Here is the complete Python solution for LeetCode #143.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedListReorderer:
def reorder_list(self, head):
if not head or not head.next:
return head
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
previous = None
current = slow.next
slow.next = None
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
first = head
second = previous
while second:
first_next = first.next
second_next = second.next
first.next = second
second.next = first_next
first = first_next
second = second_next
return head
def build_linked_list(values):
dummy = ListNode()
current = dummy
for value in values:
current.next = ListNode(value)
current = current.next
return dummy.next
def linked_list_to_list(head):
values = []
while head:
values.append(head.val)
head = head.next
return values
head = build_linked_list([1, 2, 3, 4, 5])
reorderer = LinkedListReorderer()
reorderer.reorder_list(head)
print(linked_list_to_list(head)) # Output: [1, 5, 2, 4, 3]Java Code
Here is the complete Java solution for LeetCode #143.
import java.util.ArrayList;
import java.util.List;
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
class LinkedListReorderer {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode previous = null;
ListNode current = slow.next;
slow.next = null;
while (current != null) {
ListNode nextNode = current.next;
current.next = previous;
previous = current;
current = nextNode;
}
ListNode first = head;
ListNode second = previous;
while (second != null) {
ListNode firstNext = first.next;
ListNode secondNext = second.next;
first.next = second;
second.next = firstNext;
first = firstNext;
second = secondNext;
}
}
private static ListNode buildList(int[] values) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int value : values) {
current.next = new ListNode(value);
current = current.next;
}
return dummy.next;
}
private static List<Integer> toList(ListNode head) {
List<Integer> values = new ArrayList<>();
while (head != null) {
values.add(head.val);
head = head.next;
}
return values;
}
public static void main(String[] args) {
ListNode head = buildList(new int[] {1, 2, 3, 4, 5});
LinkedListReorderer reorderer = new LinkedListReorderer();
reorderer.reorderList(head);
System.out.println(toList(head)); // [1, 5, 2, 4, 3]
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #143: Reorder List becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.