↓Skip to main content
  1. LeetCode/

LeetCode 61: Rotate List

·1 min· ·
LeetCode Medium Linked-List Two-Pointers
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-22

  • Submissions: Accepted ×2

Approach
#

Rotating right by k moves the last k nodes to the front. k may exceed the length, so take k %= n first (Linked List Template 4).

Connect the tail back to the head into a ring; walking n - k - 1 steps from the head reaches the new tail, whose next is the new head. Break there.

My Solution
#

class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head:
            return None
        n, tail = 1, head
        while tail.next:
            n, tail = n + 1, tail.next
        k %= n
        if k == 0:
            return head
        tail.next = head                             # 接成環
        new_tail = head
        for _ in range(n - k - 1):
            new_tail = new_tail.next
        new_head, new_tail.next = new_tail.next, None
        return new_head

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Reduce k modulo the length first, or it loops around many times.
  • Return directly for an empty list or k % n == 0.

Interview Explanation
#

I count the length and find the tail, reduce k modulo the length, close the ring, then walk n - k - 1 steps to the new tail and break it. Time O(n).

Related

LeetCode 19: Remove Nth Node From End of List
·2 mins
LeetCode Medium Linked-List Two-Pointers
LeetCode 19 note: from a dummy, move fast n + 1 steps ahead, then move both to the end; slow stops before the node to delete
LeetCode 237: Delete Node in a Linked List
·1 min
LeetCode Medium Linked-List
LeetCode 237 note: without the previous node, copy the next node’s value over and delete the next node instead
LeetCode 24: Swap Nodes in Pairs
·2 mins
LeetCode Medium Linked-List Recursion
LeetCode 24 note: a dummy plus pairs, rewiring prev.next, a.next and b.next together; swap nodes, not values
LeetCode 31: Next Permutation
·2 mins
LeetCode Medium Array Two-Pointers
LeetCode 31 note: from the right find the first dip i, swap it with the smallest larger value to its right, then reverse everything after i, with comparisons that include equality
LeetCode 11: Container With Most Water
·2 mins
LeetCode Medium Array Two-Pointers Greedy
LeetCode 11 note: start pointers at both ends and always move the shorter side; moving the taller side only narrows the width without raising the height
LeetCode 15: 3Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 note: sort, fix the first number, and find the other two with converging pointers, skipping equal values at all three positions to avoid duplicate triplets