Split a Circular Linked List - Problem

Given a circular linked list list of positive integers, your task is to split it into 2 circular linked lists so that the first one contains the first half of the nodes in list (exactly ceil(list.length / 2) nodes) in the same order they appeared in list, and the second one contains the rest of the nodes in list in the same order they appeared in list.

Return an array answer of length 2 in which the first element is a circular linked list representing the first half and the second element is a circular linked list representing the second half.

A circular linked list is a normal linked list with the only difference being that the last node's next node, is the first node.

Input & Output

Example 1 — Odd Number of Nodes
$ Input: head = [1,2,3,4,5]
Output: [[1,2,3],[4,5]]
💡 Note: The list has 5 nodes. First half gets ceil(5/2) = 3 nodes: [1,2,3]. Second half gets remaining 2 nodes: [4,5]. Both halves are made circular.
Example 2 — Even Number of Nodes
$ Input: head = [1,2,3,4]
Output: [[1,2],[3,4]]
💡 Note: The list has 4 nodes. First half gets ceil(4/2) = 2 nodes: [1,2]. Second half gets remaining 2 nodes: [3,4]. Both are circular.
Example 3 — Single Node
$ Input: head = [1]
Output: [[1],[]]
💡 Note: Only one node, so first half contains [1] and second half is empty. The single node points to itself.

Constraints

  • 1 ≤ list.length ≤ 105
  • 1 ≤ list[i] ≤ 106
  • The input list is a circular linked list

Visualization

Tap to expand
Split a Circular Linked List INPUT Circular Linked List 1 2 3 4 5 (5 points back to 1) head = [1,2,3,4,5] length = 5, ceil(5/2) = 3 ALGORITHM STEPS 1 Count Nodes Traverse to find length = 5 2 Calculate Split First half: ceil(5/2) = 3 nodes 3 Find Split Point Move to node 3 (end of 1st) 4 Create Two Lists Break and reconnect circles 1 2 3 4 5 List 1 List 2 | FINAL RESULT First Circular List [1,2,3] 1 2 3 Second Circular List [4,5] 4 5 Output: [[1,2,3], [4,5]] OK - Both are circular! Key Insight: Use slow/fast pointers to find the middle efficiently in O(n) time. The slow pointer stops at the split point. Remember to make BOTH resulting lists circular by connecting the last node back to the first node of each list. Time: O(n), Space: O(1) TutorialsPoint - Split a Circular Linked List | Optimal Solution (Two Pointers)
Asked in
Microsoft 15 Amazon 12 Facebook 8
28.5K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen