Find the new tail at position (length - k % length).
Break the circle after the new tail and return the new head.
💻 Code:
var rotateRight = function(head, k) {
if (!head || !head.next || k === 0) return head;
// Step 1: Calculate length and get tail node
let curr = head;
let len = 1;
while (curr.next) {
curr = curr.next;
len++;
}
// Step 2: Make it a circular list
curr.next = head;
// Step 3: Calculate the new tail position
let times = len - (k % len);
let curr2 = head;
for (let i = 1; i < times; i++) {
curr2 = curr2.next;
}
// Step 4: Break the loop and return new head
let newHead = curr2.next;
curr2.next = null;
return newHead;
};
⏱️ Time & Space Complexity:
Time Complexity: O(n), where n is the number of nodes in the list.