# Don't foget to exit early if you can ( 8ms C++ Soln. with explanation)

• I am seeing a lot of people not considering the early exit scenarios.
After the modulo operation check to see if the result is zero and bail out early if no rotation is needed.

ListNode* rotateRight(ListNode* head, int k) {

``````    if(!head || !(head->next) || k==0)

ListNode* prev = nullptr;
int nodeCount =1;

// Find the total number of nodes
// and a pointer to the tail of the list
while(temp->next)
{
nodeCount++;
temp = temp->next;
}

// The effect of rotating more than
// the nodeCount is modulo.
// Make a case of early exit if the result is 0 - no rotation needed.
if(!(k= k%nodeCount))

// Now make it a circular list

// Rotating k times has the same effect
// as making the (nodeCout-k +1)th element as the head
int skipCount = nodeCount - k;

for(int i=0;i<skipCount;++i)
{
prev = temp;
temp = temp->next;
}

// Sever the circular list
prev->next = nullptr;

}``````

• Why do you need prev? You can simplify after making the circular list

``````    temp->next = head;
k = k%nodeCount;
for(int i=0; i<nodeCount-k; i++)
temp = temp->next;