Given the head of a singly linked list and an integer k, rotate the list to the left by k positions and return the updated head.
Examples:
Input: k= 4
Output: 50 -> 10 -> 20 -> 30 -> 40 Explanation: After rotating the linked list to the left by 4 places, the 5th node, i.e node 50 becomes the head of the linked list and next pointer of node 50 points to node 10.
Input: k= 6
Output: 30 -> 40 -> 10 -> 20 Explanation: After rotating the list left by 6 positions, the node with value 30 becomes the new head, and the node with value 40 points to the node with value 10.
[Naive Approach] Shifting head node to the end k times - O(n × k) Time and O(1) Space
To rotate a linked list to the left k places, we can repeatedly move the head node to the end of the linked list k times.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*rotate(Node*head,intk){if(k==0||head==nullptr)returnhead;// rotate the list by k nodesfor(inti=0;i<k;++i){Node*curr=head;while(curr->next!=nullptr)curr=curr->next;// move the first node to the lastcurr->next=head;curr=curr->next;head=head->next;curr->next=nullptr;}returnhead;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data;if(node->next!=NULL){cout<<" -> ";}node=node->next;}cout<<endl;}intmain(){Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);head=rotate(head,6);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}structNode*rotate(structNode*head,intk){if(k==0||head==NULL)returnhead;// rotate the list by k nodesfor(inti=0;i<k;++i){structNode*curr=head;while(curr->next!=NULL)curr=curr->next;// move the first node to the lastcurr->next=head;curr=curr->next;head=head->next;curr->next=NULL;}returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d",node->data);if(node->next!=NULL){printf(" -> ");}node=node->next;}printf("\n");}intmain(){structNode*head=createNode(10);head->next=createNode(20);head->next->next=createNode(30);head->next->next->next=createNode(40);head=rotate(head,6);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNoderotate(Nodehead,intk){if(k==0||head==null)returnhead;// rotate the list by k nodesfor(inti=0;i<k;++i){Nodecurr=head;while(curr.next!=null)curr=curr.next;// move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null){System.out.print(" -> ");}node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);}}
Python
classNode:def__init__(self,newData):self.data=newDataself.next=Nonedefrotate(head,k):ifk==0orheadisNone:returnhead# rotate the list by k nodesfor_inrange(k):curr=headwhilecurr.nextisnotNone:curr=curr.next# move the first node to the lastcurr.next=headcurr=curr.nexthead=head.nextcurr.next=NonereturnheaddefprintList(node):whilenodeisnotNone:print(node.data,end="")ifnode.next!=None:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":head=Node(10)head.next=Node(20)head.next.next=Node(30)head.next.next.next=Node(40)head=rotate(head,6)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}classGfG{staticNodeRotate(Nodehead,intk){if(k==0||head==null)returnhead;// rotate the list by k nodesfor(inti=0;i<k;++i){Nodecurr=head;while(curr.next!=null)curr=curr.next;// move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data);if(node.next!=null){Console.Write(" -> ");}node=node.next;}Console.WriteLine();}staticvoidMain(){Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=Rotate(head,6);printList(head);}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionrotate(head,k){if(k===0||head===null){returnhead;}// rotate the list by k nodesfor(leti=0;i<k;++i){letcurr=head;while(curr.next!==null){curr=curr.next;}// move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}functionprintList(node){letresult='';while(node!==null){result+=node.data;if(node.next!=null){result+=" -> ";}node=node.next;}console.log(result.trim());}// Driver Codelethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);
Output
30 -> 40 -> 10 -> 20
[Expected Approach] By changing pointer of kth node - O(n) Time and O(1) Space
The idea is to first convert the linked list to circular linked list by updating the next pointer of last node to the head of linked list. Then, traverse to the kth node and update the head of the linked list to the (k+1)th node. Finally, break the loop by updating the next pointer of kth node to NULL.
How to handle large values of k?
For a linked list of size n, if we rotate the linked list to the left by n places, then the linked list will remain unchanged and if we rotate the list to the left by (n + 1) places, then it is same as rotating the linked list to the left by 1 place. Similarly, if we rotate the linked list k (k >= n) places to the left, then it is same as rotating the linked list by (k % n) places. So, we can simply update k with k % n to handle large values of k.
Illustrations:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*rotate(Node*head,intk){if(k==0||head==nullptr)returnhead;Node*curr=head;intlen=1;// find the length of linked listwhile(curr->next!=nullptr){curr=curr->next;len+=1;}// modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// make the linked list circularcurr->next=head;// traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr->next;// update the (k + 1)th node as the new headhead=curr->next;// break the loop by updating next pointer of kth nodecurr->next=nullptr;returnhead;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";if(node->next!=NULL){cout<<"-> ";}node=node->next;}cout<<endl;}intmain(){Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);head=rotate(head,6);printList(head);return0;}
C
#include<stdio.h>structNode{intdata;structNode*next;};structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}structNode*rotate(structNode*head,intk){if(k==0||head==NULL)returnhead;structNode*curr=head;intlen=1;// find the length of linked listwhile(curr->next!=NULL){curr=curr->next;len+=1;}// modulo k with length of linked list to// handle large values of kk%=len;if(k==0)returnhead;// make the linked list circularcurr->next=head;// traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr->next;// update the (k + 1)th node as the new headhead=curr->next;// break the loop by updating next pointer// of kth nodecurr->next=NULL;returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d",node->data);if(node->next!=NULL){printf(" -> ");}node=node->next;}printf("\n");}intmain(){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40structNode*head=createNode(10);head->next=createNode(20);head->next->next=createNode(30);head->next->next->next=createNode(40);head=rotate(head,6);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNoderotate(Nodehead,intk){if(k==0||head==null)returnhead;Nodecurr=head;intlen=1;// find the length of linked listwhile(curr.next!=null){curr=curr.next;len+=1;}// modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// make the linked list circularcurr.next=head;// traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr.next;// update the (k + 1)th node as the new headhead=curr.next;// break the loop by updating next pointer// of kth nodecurr.next=null;returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null){System.out.print(" -> ");}node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);}}
Python
classNode:def__init__(self,newData):self.data=newDataself.next=Nonedefrotate(head,k):ifk==0orheadisNone:returnheadcurr=headlength=1# find the length of the linked listwhilecurr.nextisnotNone:curr=curr.nextlength+=1# modulo k with length of linked list to handle# large values of kk%=lengthifk==0:curr.next=Nonereturnhead# make the linked list circularcurr.next=head# traverse the linked list to find the kth nodecurr=headfor_inrange(1,k):curr=curr.next# update the (k + 1)th node as the new headnewHead=curr.next# break the loop by updating the next pointer# of kth nodecurr.next=NonereturnnewHeaddefprintList(node):whilenodeisnotNone:print(node.data,end="")ifnode.next!=None:print(" -> ",end="")node=node.nextif__name__=="__main__":# create a hard-coded linked list# 10 -> 20 -> 30 -> 40head=Node(10)head.next=Node(20)head.next.next=Node(30)head.next.next.next=Node(40)head=rotate(head,6)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}classGfG{staticNoderotate(Nodehead,intk){if(k==0||head==null)returnhead;Nodecurr=head;intlen=1;// find the length of linked listwhile(curr.next!=null){curr=curr.next;len+=1;}// modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// make the linked list circularcurr.next=head;// traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr.next;// update the (k + 1)th node as the new headNodenewHead=curr.next;// break the loop by updating next pointer// of kth nodecurr.next=null;returnnewHead;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data);if(node.next!=null){Console.Write(" -> ");}node=node.next;}Console.WriteLine();}publicstaticvoidMain(){Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionrotate(head,k){if(k===0||head===null)returnhead;letcurr=head;letlen=1;// find the length of linked listwhile(curr.next!==null){curr=curr.next;len+=1;}// modulo k with length of linked list to handle// large values of kk%=len;if(k===0){curr.next=null;returnhead;}// make the linked list circularcurr.next=head;// traverse the linked list to find the kth nodecurr=head;for(leti=1;i<k;i++)curr=curr.next;// update the (k + 1)th node as the new headletnewHead=curr.next;// break the loop by updating next pointer of kth nodecurr.next=null;returnnewHead;}functionprintList(node){letoutput='';while(node!==null){output+=node.data;if(node.next!==null){output+=" -> ";}node=node.next;}console.log(output.trim());}// Driver Codelethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);