← Home

725. Split Linked List in Parts

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

This is one of those problems where the clean idea matters more than the amount of code. For 725. Split Linked List in Parts, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. 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.

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 splitListToParts, parts, tails.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

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) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 12 ms, faster than 74.84% of C++ online submissions for Split Linked List in Parts.
02//Memory Usage: 9.9 MB, less than 9.09% of C++ online submissions for Split Linked List in Parts.
03/**
04 * Definition for singly-linked list.
05 * struct ListNode {
06 *     int val;
07 *     ListNode *next;
08 *     ListNode(int x) : val(x), next(NULL) {}
09 * };
10 */
11class Solution {
12public:
13    vector<ListNode*> splitListToParts(ListNode* root, int k) {
14        //hint: If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
15        vector<int> inputs;
16        ListNode* cur = root;
17        while(cur){
18            inputs.push_back(cur->val);
19            cur = cur->next;
20        }
21        
22        //cumulative size for each part
23        vector<int> parts(k);
24        for(int i = 0; i < k; i++){
25            parts[i] = inputs.size()/k + (i < inputs.size()%k) + ((i>0) ? parts[i-1] : 0);
26        }
27        
28        //need to "new ListNode" in a loop!
29        //if "new" while initilaizing vector, all the elements point to the same position
30        // vector<ListNode*> ans(k, new ListNode(0));
31        vector<ListNode*> ans(k, NULL);
32        for(int i = 0; i < k; i++){
33            if((i > 0 && parts[i] - parts[i-1] == 0) || parts[i] == 0){
34                ans[i] = NULL;
35            }else{
36                ans[i] = new ListNode(-1);
37            }
38        }
39        
40        vector<ListNode*> tails(k);
41        for(int i = 0; i < k; i++){
42            tails[i] = ans[i];
43        }
44        
45        int partId = 0;
46        for(int i = 0; i < inputs.size(); i++){
47            if(i >= parts[partId]){
48                partId++;
49            }
50            tails[partId]->val = inputs[i];
51            if(i+1 < parts[partId]){
52                tails[partId]->next = new ListNode(0);
53                tails[partId] = tails[partId]->next;
54            }
55        }
56        
57        return ans;
58    }
59};
60
61//Approach #2: Split Input List
62//Runtime: 12 ms, faster than 74.84% of C++ online submissions for Split Linked List in Parts.
63//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Split Linked List in Parts.
64//time: O(N+k), space: O(k)
65/**
66 * Definition for singly-linked list.
67 * struct ListNode {
68 *     int val;
69 *     ListNode *next;
70 *     ListNode(int x) : val(x), next(NULL) {}
71 * };
72 */
73class Solution {
74public:
75    vector<ListNode*> splitListToParts(ListNode* root, int k) {
76        ListNode* cur = root;
77        int N = 0;
78        while(cur){
79            N++;
80            cur = cur->next;
81        }
82        
83        int width = N/k, rem = N%k;
84        vector<ListNode*> ans(k, NULL);
85        
86        cur = root;
87        for(int i = 0; i < k; i++){
88            //the head of current part
89            ListNode* head = cur;
90            ListNode* prev = cur;
91            //prev becomes the last node of current part
92            //(a.k.a, the previous node of next part)
93            for(int j = 0; j < width + (i < rem ? 1 : 0) - 1; j++){
94                if(prev) prev = prev->next;
95            }
96            if(prev){
97                //make cur points to the start of next part 
98                cur = prev->next;
99                //cur current part and next part
100                prev->next = NULL;
101            }
102            ans[i] = head;
103        }
104        
105        return ans;
106    }
107};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
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.