TIC
The Interns Company

Reorder List

MediumAcceptance: 51.7%

Problem Statement

You are given the head of a singly linked list. The list can be represented as L0 → L1 → … → Ln - 1 → Ln. Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed.

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 10^4]
  • 1 <= Node.val <= 1000

Input Format:

  • The head of a singly linked list

Output Format:

  • Reorder the list in-place according to the pattern described

Examples:

Example 1:

Input:

head = [1,2,3,4]

Output:

[1,4,2,3]

Explanation:

The list has been reordered from 1→2→3→4 to 1→4→2→3.

Example 2:

Input:

head = [1,2,3,4,5]

Output:

[1,5,2,4,3]

Explanation:

The list has been reordered from 1→2→3→4→5 to 1→5→2→4→3.

Solutions

Three-Step Approach: Find Middle, Reverse Second Half, Merge

Time: O(n)
Space: O(1)

Find the middle of the linked list, reverse the second half, and then merge the two halves alternately.

Using a Stack Approach

Time: O(n)
Space: O(n)

Use a stack to store the second half of the linked list nodes and then rearrange them.

Algorithm Walkthrough

Example input: nums = []

Step-by-step execution:

  1. Initial list: 1 -> 2 -> 3 -> 4
  2. Step 1: Find the middle. slow = node with value 2, fast = node with value 4
  3. Step 2: Reverse second half. Reversed second half: 4 -> 3 -> null
  4. Break the list: First half: 1 -> 2 -> null, Second half: 4 -> 3 -> null
  5. Step 3: Merge alternately:
  6. First iteration: 1 -> 4 -> 2 -> null, remaining second: 3 -> null
  7. Second iteration: 1 -> 4 -> 2 -> 3 -> null, remaining second: null
  8. Final reordered list: 1 -> 4 -> 2 -> 3 -> null

Hints

Hint 1
Can you split the list into two halves?
Hint 2
After splitting, try reversing the second half.
Hint 3
Once you have two halves (with the second half reversed), you can merge them alternately.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize finding the middle, reversing the second half, and merging the two halves alternately.

Key visualization elements:

  • middle finding
  • reversing
  • merging

Implementation Notes

This problem tests understanding of linked list manipulations, finding the middle of a list, and in-place reversal. The three-step approach is memory efficient and elegant.