Find the new tail at position (length - k % length).
Break the circle after the new tail and return the new head.
š» Code:
varrotateRight=function(head,k){if (!head||!head.next||k===0)returnhead;// Step 1: Calculate length and get tail nodeletcurr=head;letlen=1;while (curr.next){curr=curr.next;len++;}// Step 2: Make it a circular listcurr.next=head;// Step 3: Calculate the new tail positionlettimes=len-(k%len);letcurr2=head;for (leti=1;i<times;i++){curr2=curr2.next;}// Step 4: Break the loop and return new headletnewHead=curr2.next;curr2.next=null;returnnewHead;};
ā±ļø Time & Space Complexity:
Time Complexity: O(n), where n is the number of nodes in the list.
Space Complexity: O(1), constant space used.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)