KatInterview

Collect minimum values with adjacent deletions

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaplinked-listsimulation

Last updated

Tests simulation using a priority queue with lazy deletion and a linked list to repeatedly remove the smallest remaining element and its current neighbors.

You are given an array vals of positive integers arranged in a row. You repeatedly perform the following operation until every element has been removed:

  1. Among all remaining elements, select the one with the smallest value. If multiple share the smallest value, pick the one that appears earliest in the original array order.
  2. Add this element's value to a running sum.
  3. Remove the selected element from the row. Additionally, remove up to two adjacent elements: the nearest surviving element to its left (if one exists) and the nearest surviving element to its right (if one exists).

Return the total sum accumulated once all elements have been removed.

Constraints:

  • 0 <= len(vals) <= 10^5
  • 1 <= vals[i] <= 10^9
  • When the selected element has no surviving neighbor on one side, only the neighbor on the other side (if any) is removed.
  • Removing an element means it is no longer present in the row and cannot be selected or serve as a neighbor in future steps.
  • The relative order of surviving elements never changes; only elements are removed, never rearranged.

Examples

Example 1

Input: collect_lightest_with_neighbors([4, 3, 2, 1])

Output: 4

Example 2

Input: collect_lightest_with_neighbors([1])

Output: 1

Example 3

Input: collect_lightest_with_neighbors([1, 2, 3, 4, 5])

Output: 9

Hints

Hint 1

A min-heap of (value, original_index) pairs gives you the smallest value with the correct tie-break for free, since survivors keep their relative order.

Hint 2

Use lazy deletion: maintain a boolean alive array and skip heap entries whose index is already marked dead.

Hint 3

Maintain prev and next pointers in a doubly linked list over original indices so you can find current neighbors and unlink in O(1) per removal.