Search~20 min2s · 256 MBtarget O(n + k) time, O(1) spaceclassic twin: lc-725linked-lists
A search app keeps the matches for a query as a chain of nodes, one node for each result. The app wants to show the results on k pages that are as even as possible.
The page sizes may differ by at most one, and a page that is larger must come before a page that is smaller. When there are fewer results than pages, the last pages are empty. A query can have up to 100,000 results.
Write split_results(head, k).
head is the first node of the result chain, or null when there are no results. Each node's val is a result id.k is the number of pages.k consecutive pages, in the original order. Page sizes differ by at most one, and no page is larger than any page before it.k rows. Each row is the list of ids on that page, in order. An empty page is an empty row.The tests give head as the list of values from the head.
Input: head = [5, 9, 2, 7, 1, 8, 3, 6], k = 3
Output: [[5, 9, 2], [7, 1, 8], [3, 6]]| Step | Page | Size | Nodes on the page | Left after the cut |
|---|---|---|---|---|
| [1] | n = 8 | |||
| [2] | base = 8 // 3 = 2, extra = 8 % 3 = 2 | |||
| [4] | 0 | 3 | 5 → 9 → 2 | 7 → 1 → 8 → 3 → 6 |
| [4] | 1 | 3 | 7 → 1 → 8 | 3 → 6 |
| [4] | 2 | 2 | 3 → 6 | none |
Eight results on three pages: 8 = 3 × 2 + 2, so every page gets 2 results, and the first two pages get one more.
Input: head = [4, 6], k = 5
Output: [[4], [6], [], [], []]There are fewer results than pages, so the last three pages are empty.
Input: head = [], k = 2
Output: [[], []]No results: every page is empty, and there are still k of them.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^61 ≤ k ≤ 10^5Reading each result by position, with a walk from the head, costs about n² / 2 hops: about 5 × 10^9 at this size.
Counting once and cutting while you walk costs about 2 × 10^5 hops. The k rows add up to k more steps.