LeetCode 2674: Split a Circular Linked List Solution

Master LeetCode problem 2674 (Split a Circular Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2674. Split a Circular Linked List

Problem Explanation

Explanation:

The problem asks us to split a circular linked list into two separate circular linked lists. We need to find the two halve points and then rewire the pointers accordingly.

Algorithm:

  1. Find the middle of the circular linked list using the slow and fast pointer technique.
  2. Break the circular link by setting the next pointer of the middle node to null.
  3. Set the head of the second half to the node next to the middle node.
  4. Update the next pointer of the last node of the first half to point to the head of the first half.
  5. Update the next pointer of the last node of the second half to point to the head of the second half.

Time Complexity: O(n) where n is the number of nodes in the circular linked list.

Space Complexity: O(1)

:

Solution Code

class ListNode {
    int val;
    ListNode next;
    
    public ListNode(int val) {
        this.val = val;
    }
}

public ListNode[] splitList(ListNode head) {
    if (head == null || head.next == head) {
        return new ListNode[] {head, null};
    }
    
    ListNode slow = head;
    ListNode fast = head;
    
    while (fast.next != head && fast.next.next != head) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    ListNode head2 = slow.next;
    slow.next = null;
    
    ListNode curr = head2;
    while (curr.next != head) {
        curr = curr.next;
    }
    
    curr.next = head2;
    
    return new ListNode[] {head, head2};
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2674 (Split a Circular Linked List)?

This page provides optimized solutions for LeetCode problem 2674 (Split a Circular Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2674 (Split a Circular Linked List)?

The time complexity for LeetCode 2674 (Split a Circular Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2674 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2674 in Java, C++, or Python.

Back to LeetCode Solutions