Link

Medium Linked List Two Pointers

Adobe

Amazon

Bloomberg

2020-10-07

61. Rotate List

Question:

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

Solution:

There are two different ways of using the pointers
Time Complexity: O(n) Both are using the same idea: finding the connection point and relink the list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        int counter = 1;
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
            counter++;
        }
        k = k % counter;
        if (k == 0) {
            return head;
        }
        ListNode newTail = head;
        for (int i = 0; i < counter - k - 1; i++){
            newTail = newTail.next;
        }
        ListNode result = newTail.next;
        tail.next = head;
        newTail.next = null;
        
        return result;
    }
}

Use two pointers, one is faster than the other with the gap of k.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        int counter = 0;
        
        // Two Pointers
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null) {
            fast = fast.next;
            counter++;
        }
        k = k % counter;
        fast = head;
        
        // The difference between two pointers is k
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        
        // Two pointer move to the end
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        
        // slow is pointing to the tail and fast is pointing to the connection point
        // slow.next is the head
        fast.next = head;
        head = slow.next;
        slow.next = null;
        
        return head;
    }
}