Bird
Raised Fist0
Interview Prepfast-slow-pointersmediumGoogleAmazon

Split Linked List in Parts

Choose your preparation mode3 modes available
Steps
setup

Initialize total_nodes and current pointer

Set total_nodes to 0 and current pointer to head of the list to start counting nodes.

💡 Counting nodes is essential to determine how to split the list evenly.
Line:total_nodes = 0 current = head
💡 We start with no nodes counted and a pointer at the list head.
📊
Split Linked List in Parts - Watch the Algorithm Execute, Step by Step
Watching each pointer move and link break helps you understand how the list is divided evenly and why some parts may be empty.
Step 1/18
·Active fillAnswer cell
advance
1
2
3
advance
1
2
3
Result: 1
advance
1
2
3
Result: 2
advance
1
2
3
Result: 3
advance
1
2
3
Result:
Part size:0
Remainder:3
advance
1
2
3
Result:
Parts:[null, null, null, null, null]
connect
1
2
3
Result:
Parts:[[1], null, null, null, null]
Remainder:2
advance
1
2
3
Result:
Parts:[[1], null, null, null, null]
detach
1
2
3
Result:
Parts:[[1], null, null, null, null]
connect
1
2
3
Result:
Parts:[[1], [2], null, null, null]
Remainder:1
advance
1
2
3
Result:
Parts:[[1], [2], null, null, null]
detach
1
2
3
Result:
Parts:[[1], [2], null, null, null]
connect
1
2
3
Result:
Parts:[[1], [2], [3], null, null]
Remainder:0
advance
1
2
3
Result:
Parts:[[1], [2], [3], null, null]
detach
1
2
3
Result:
Parts:[[1], [2], [3], null, null]
connect
1
2
3
Result:
Parts:[[1], [2], [3], null, null]
connect
1
2
3
Result:
Parts:[[1], [2], [3], null, null]
reconstruct
1
2
3
Result: [[1], [2], [3], null, null]

Key Takeaways

The algorithm counts nodes first to determine exact part sizes and remainder for even distribution.

This counting step is crucial and often overlooked; without it, splitting evenly is impossible.

Parts with remainder get one extra node, ensuring the first few parts are larger if nodes don't divide evenly.

Visualizing remainder distribution clarifies why some parts have one node and others are empty.

Breaking links inline isolates parts without extra memory, showing efficient in-place list manipulation.

Seeing links broken step-by-step reveals how the list is physically split, which is hard to grasp from code alone.