01 · Question
Given an integer array and k ≥ 2, repeatedly replace the leftmost block of k equal adjacent values with their sum. Return the fully compressed array.
Examples: [1,9,9,3,3,3,4], k=3 → [1,27,4]; [8,4,2,2], k=2 → [16]; [4,4,4], k=5 → [4,4,4]. Empty input returns an empty array.
02 · Analysis
Store (value, count) groups. In the settled stack, adjacent groups have different values and each count is below k. Merge a new value into the last run when equal. If its count reaches k, pop that run, multiply the value by k, and process it again against the newly exposed top.
For k=3, [(1,1),(9,2),(3,2)] + 3 becomes [(1,1),(9,2)] + 9, then [(1,1)] + 27.
Re-expand the runs to produce the answer. Each merge reduces the represented length by k−1: O(n) time and O(n) space under constant-time arithmetic. The iterative loop avoids recursion-depth failures during long cascades. Go's integer type must be large enough for merged sums.