AlgoInsight

DSA problem

Rotate List

MediumLinked ListPattern: Linked Listtop150AmazonMicrosoftBloombergAppleLinkedIn

Given the head of a linked list, rotate the list to the right by k places. Rotating to the right by one place means the last node moves to the front and every other node shifts one position toward the tail.

The first subtlety is that k may be much larger than the list length n. Rotating by n places returns the original list, so the effective number of rotations is k mod n. If this remainder is zero, the list is unchanged.

A second observation simplifies the rewiring: rotating to the right by k is equivalent to making a new break in the list. The new head becomes the node at position n - (k mod n) from the start, and the node just before it becomes the new tail.

The intuition is to first walk the list to count its length and find the old tail. Connect that tail back to the head, forming a temporary ring. Then advance n - (k mod n) steps from the head to locate the new tail, set the new head as its successor, and finally break the ring by setting the new tail's next to null. This solves the problem in a single conceptual pass with constant extra space.

Examples

Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Explanation: Rotating right once gives [5,1,2,3,4], and rotating again gives [4,5,1,2,3].
Example 2
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Explanation: With n = 3, the effective rotation is 4 mod 3 = 1. Rotating right by 1 moves the last node 2 to the front, giving [2,0,1].
Example 3
Input: head = [1,2], k = 0
Output: [1,2]
Explanation: A rotation of 0 places leaves the list unchanged.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersin-placepointers

Browse all DSA problems