Collect minimum values with adjacent deletions
Heaps, Sorting & SearchAuto-graded · 25 test casesLast 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:
- 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.
- Add this element's value to a running sum.
- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a simulation problem where two operations need to be efficient: finding the smallest remaining element (with tie-break by earliest position) and finding its current left and right neighbors.
Selection. Build a min-heap of (value, original_index) tuples. Python compares tuples element by element, so equal values are ordered by smaller index. Because removals never reorder survivors, original index order matches current positional order, making the tie-break correct without any extra work. The heap does not support deleting arbitrary elements, so use lazy deletion: keep an alive boolean array and skip any heap entry whose index is already marked dead.
Neighbor lookup. Maintain a doubly linked list using prev and nxt arrays over the original indices. The invariant is that prev[x] and nxt[x] always point to the nearest live element on each side of every live x, with -1 and n as sentinels meaning "no neighbor." Unlinking a node splices its two neighbors together in O(1), preserving the invariant. Read both neighbors before any unlinking so the pointers stay consistent.
Each iteration pops the heap, discards stale entries, adds the value to the total, then unlinks the selected element and both neighbors. The loop ends when the heap is empty, at which point every element has been removed.
Complexity
- Time: O(n log n). Each element is pushed once (via heapify) and popped at most once, each pop costing O(log n). Every unlink is O(1).
- Space: O(n) for the heap,
alive,prev, andnxtarrays.
Reference Solution
from typing import List
import heapq
def collect_lightest_with_neighbors(vals: List[int]) -> int:
n = len(vals)
if n == 0:
return 0
# Doubly linked list over indices; -1 and n act as "no neighbor" sentinels.
prev = list(range(-1, n - 1))
nxt = list(range(1, n + 1))
alive = [True] * n
# (value, index) ordering gives "smallest value, then earliest index" for free.
heap = [(v, i) for i, v in enumerate(vals)]
heapq.heapify(heap)
def unlink(x: int) -> None:
p, q = prev[x], nxt[x]
if p >= 0:
nxt[p] = q
if q < n:
prev[q] = p
alive[x] = False
total = 0
while heap:
w, i = heapq.heappop(heap)
if not alive[i]: # lazy deletion: stale entry
continue
total += w
left, right = prev[i], nxt[i] # current live neighbors
unlink(i)
if left >= 0:
unlink(left)
if right < n:
unlink(right)
return total