← Home

61. Rotate List

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
61

The trick here is to name the state correctly, then let the implementation follow. For 61. Rotate List, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • time: O(N), space: O(1)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are rotateRight.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 8 ms, faster than 81.03% of C++ online submissions for Rotate List.
02//Memory Usage: 11.9 MB, less than 20.29% of C++ online submissions for Rotate List.
03//time: O(N), space: O(1)
04/**
05 * Definition for singly-linked list.
06 * struct ListNode {
07 *     int val;
08 *     ListNode *next;
09 *     ListNode() : val(0), next(nullptr) {}
10 *     ListNode(int x) : val(x), next(nullptr) {}
11 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
12 * };
13 */
14class Solution {
15public:
16    ListNode* rotateRight(ListNode* head, int k) {
17        ListNode *slow = head, *fast = head;
18        int len = 0;
19        
20        for(ListNode* cur = head; cur; cur = cur->next) ++len;
21        
22        if(len <= 1) return head;
23        
24        k = k % len;
25        if(k == 0) return head;
26        
27        for(int i = 0; i < k; ++i) fast = fast->next;
28        
29        while(slow->next && fast->next){
30            slow = slow->next;
31            fast = fast->next;
32        }
33        
34        //now slow is the previous node of the new head
35        ListNode* newhead = slow->next;
36        slow->next = nullptr;
37        //fast is the last node of original list
38        fast->next = head;
39        
40        return newhead;
41    }
42};
43
44//cleaner
45//https://leetcode.com/problems/rotate-list/discuss/22735/My-clean-C%2B%2B-code-quite-standard-(find-tail-and-reconnect-the-list)
46//Runtime: 8 ms, faster than 81.03% of C++ online submissions for Rotate List.
47//Memory Usage: 12 MB, less than 14.57% of C++ online submissions for Rotate List.
48class Solution {
49public:
50    ListNode* rotateRight(ListNode* head, int k) {
51        if(!head || !head->next || k == 0) return head;
52        ListNode* cur = head;
53        int len = 1;
54        
55        //find tail
56        while(cur->next){
57            ++len;
58            cur = cur->next;
59        }
60        //now cur is the last node of original list
61        
62        //connect tail and head
63        cur->next = head;
64        
65        //find the tail of new list
66        for(int i = 0; i < len - (k%len); ++i){
67            cur = cur->next;
68        }
69        
70        //head of new list is the next node of tail of new list
71        head = cur->next;
72        cur->next = nullptr;
73        
74        return head;
75    }
76};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.