Rotate List

Medium

Topics
Linked ListTwo Pointers

Given the head of a linked list, rotate the list to the right by k places and return the new head.

Example 1

before12345null
after45123null
Rotating right by 2 moves the shaded tail to the front. Since k can far exceed the length, the real shift is k % 5 = 2 — taking k literally is the usual timeout.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2

before012null
after201null
Input:  head = [0,1,2], k = 4
Output: [2,0,1]

Constraints

  • 0 <= number of nodes <= 500
  • -100 <= Node.val <= 100
  • 0 <= k <= 2*10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Rotating right by k moves the last k nodes to the front, so the new head is at index n - k and the new tail is just before it. No node needs to move; two pointer writes do the whole job.

Two details carry the problem. k reaches 2×10⁹ while the list holds at most 500 nodes, so k must be reduced modulo n before anything else — otherwise you walk two billion steps. And closing the list into a ring first means the cut is a single operation instead of a splice.

Approach

  1. Walk to the tail, counting the nodes to get n.
  2. Reduce k modulo n; if it is zero the list is unchanged.
  3. Join the tail to the head, forming a ring.
  4. Walk n - k - 1 steps from the head to reach the new tail.
  5. Take its successor as the new head and cut the ring there.

Dry Run

input  1 -> 2 -> 3 -> 4 -> 5      k = 2

n = 5,  k % n = 2,  new head is at index n - k = 3

close the ring     1 -> 2 -> 3 -> 4 -> 5 -+
                   ^----------------------+
walk to index 2    new tail = node 3
cut after it       new head = node 4

answer  4 -> 5 -> 1 -> 2 -> 3

  [0,1,2]  k = 4             -> 2 -> 0 -> 1     k % 3 = 1
  [1,2]    k = 2000000000    -> 1 -> 2          k % 2 = 0, untouched
  []       k = 5             -> empty
  [1]      k = 99            -> 1

Complexity

  • Time — O(n): one pass to measure and one partial pass to the cut point.
  • Space — O(1).

Common Pitfalls

  • Rotating one position at a time, k times. With k up to 2×10⁹ that never finishes; the modulus is not an optimisation, it is the difference between terminating and not.
  • Taking the modulus before counting the nodes, which needs n and so cannot work.
  • Dividing by n without handling the empty list. The early return for a null or single-node head is what keeps the modulus safe.
  • Cutting at n - k steps instead of n - k - 1. The walk has to stop on the new tail, not on the new head.
  • Leaving the ring closed. Forgetting the final new_tail.next = None returns a circular list, and anything that traverses it runs forever.
  • Rotating left instead of right. Rotating right by k is rotating left by n - k; mixing them up passes the symmetric cases and fails the rest.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def rotateRight(self, head, k):
        if not head or not head.next:
            return head
        n = 1
        tail = head
        while tail.next:
            tail = tail.next
            n += 1
        k %= n
        if k == 0:
            return head
        tail.next = head
        steps = n - k
        new_tail = head
        for _ in range(steps - 1):
            new_tail = new_tail.next
        new_head = new_tail.next
        new_tail.next = None
        return new_head
Asked at Nvidia
SensAI
Beta
Tap the mic to stop voice mode