Skip to content

ORIGINAL CODING QUESTION

Reverse a chain in fixed-size groups

A sprint board stores task cards as a linked chain; each node holds a card value and the index of the next node. Walking from head, split the chain into consecutive groups of k cards. Reverse the order inside every complete group, and keep a final group of fewer than k cards in its original order. Return the checksum of the resulting chain: the sum over 1-based positions p of p times the card value at that position.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n head, then n pairs (value next) describing nodes 0 to n-1 in index order. next is the index of the following node, or -1 for the last node. Then k. Print the checksum.

Constraints

1 ≤ n ≤ 200; values in [-1000, 1000]; following next from head visits every node exactly once and then reaches -1. 1 ≤ k ≤ 200.

Example 1

Input

5 0
1 1
2 2
3 3
4 4
5 -1
2

Output

53

The chain becomes 2, 1, 4, 3, 5, so the checksum is 2 + 2 + 12 + 12 + 25 = 53.

Example 2

Input

4 3
10 -1
20 0
30 1
40 2
3

Output

240

The chain 40, 30, 20, 10 becomes 20, 30, 40, 10, giving 20 + 60 + 120 + 40 = 240.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Before reversing a group, check that k nodes actually remain.

Hint 2

Reverse one group by rewiring next pointers, with the node after the group as the initial previous pointer.

Hint 3

Link the node before the group to the group’s new first node; the group’s old first node becomes the node before the next group.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →