Reorder List

35 min · reorderList()

Picture a row of cards. You take the front card, then the back card, then the new front, then the new back. That alternating rhythm is the order you need here.

A linked list is a chain of nodes where each node's next field links to the one after it. Its nodes currently appear as L0 → L1 → ... → Ln-1, where L0 is the first node and Ln-1 is the last. Rearrange them into L0 → Ln-1 → L1 → Ln-2 → ..., then return the head of the reordered list.

A few ground rules:

  • Take one node from the front, then one from the back, until every node is used.
  • Keep every stored value unchanged; you're rearranging nodes, not editing their data.
  • The first node remains the head.
  • Odd and even lengths both follow the same front-back rhythm.

Constraints

  • 1 <= length <= 10_000
  • -1_000_000_000 <= Node.val <= 1_000_000_000

Hints

Write the order down

An array makes the target order easy to see: use one index at the front and another at the back, alternating between them. That's a useful baseline, even though it costs O(n) extra space.

Turn one list into two

Find the middle. If you reverse the second half, the nodes you need from the back become available from left to right.

Weave without a cycle

Cut the link at the middle before reversing. Then alternate one node from the first half and one from the reversed second half, saving both next pointers before you overwrite either one.

Follow-up

Can you rearrange the existing nodes in O(n) time and O(1) extra space, without an array or a newly built list?

Visible cases

Examples

Example 1

ready
Input
head = [
  1,
  2,
  3,
  4
]
Expected
[
  1,
  4,
  2,
  3
]
Why
take from the front, back, front, then back

Example 2

ready
Input
head = [
  1,
  2,
  3,
  4,
  5
]
Expected
[
  1,
  5,
  2,
  4,
  3
]
Why
the middle node is used once at the end

Example 3

ready
Input
head = [
  1
]
Expected
[
  1
]
Why
one node is already in the requested order

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite