Sum Lightest Weights Under Neighbor Deletions
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
A row of items is described by a list weights of positive integers. Starting with an accumulated total of 0, repeat the procedure below until no items are left in the row:
- Locate the minimum weight among all items still present. Whenever multiple surviving items share that minimum weight, select the leftmost one (lowest current position).
- Add the selected item's weight to the accumulated total.
- Erase the selected item from the row along with its immediate current left neighbor (if present) and its immediate current right neighbor (if present). Erasing items closes any gap between the surviving items on either side so they become directly adjacent in subsequent rounds.
Return the final accumulated total once the row becomes empty (or 0 immediately when weights starts empty).
def sum_minima_with_removals(weights: List[int]) -> int:
Examples
Example 1
Input: weights = [8, 3, 6, 2, 9]
Output: 5
Explanation:
- Round 1 selects 2 (the lightest item), adds 2 to the total, and deletes 2 together with its neighbors 6 and 9, leaving [8, 3].
- Round 2 selects 3, adds 3 to the total, and deletes 3 along with its sole remaining neighbor 8, leaving [].
- Total accumulated weight: 2 + 3 = 5.
Example 2
Input: weights = [4, 10, 2, 7, 5, 6]
Output: 12
Explanation:
- Round 1 selects 2, adds 2, and deletes 10, 2, and 7. Closing the gap leaves [4, 5, 6], making 4 and 5 neighbors.
- Round 2 selects 4, adds 4, and deletes 4 along with its new right neighbor 5, leaving [6].
- Round 3 selects 6, adds 6, and deletes 6.
- Total accumulated weight: 2 + 4 + 6 = 12.
Example 3
Input: weights = [3, 3, 8]
Output: 11
Explanation:
- Round 1 breaks the tie between the two 3s by choosing the leftmost 3, adding 3 and deleting both 3s while leaving [8].
- Round 2 selects 8, adding 8 for a final total of 3 + 8 = 11.
Constraints
0 <= len(weights) <= 10^51 <= weights[i] <= 10^9
Step-by-step walkthrough
Understand the rules and the two subtle traps
We are given a row of items with positive integer
weights. Until the row is empty, we repeat the same three actions:- Choose the lightest remaining item. If several remaining items tie for the lightest weight, choose the leftmost one (the smallest current index).
- Add that item's weight to our running total.
- Remove that item and up to two items currently standing immediately next to it (one on the left and one on the right, if they exist).
An empty input list has nothing to pick, so its total is
0.Two details in the rules decide everything:
- Ties go to the leftmost survivor. In Example 3 (
[3, 3, 8]), picking the left3removes[3, 3]and leaves[8], giving3 + 8 = 11. Picking the right3first would have removed all three items at once and given3. - Neighbors mean current neighbors, not original neighbors. Deleting a group in the middle closes the gap so items that started far apart become adjacent, as in Example 2:
Start: [4, 10, 2, 7, 5, 6] ^---^---^ Round 1 picks 2 -> removes 10, 2, 7. Gap closes: [4, 5, 6] -> 4 and 5 are now neighbors! Round 2 picks 4 -> removes 4 and its NEW right neighbor 5. Remaining: [6] Round 3 picks 6 -> removes 6. Total = 2 + 4 + 6 = 12.Start with brute force and see why it is too slow
The most direct translation is to keep a Python list, scan it from left to right each round to find the first minimum, add that weight, and delete the slice around it:
def brute_sum_minima(weights): items = list(weights) total = 0 while items: best = 0 for j in range(1, len(items)): if items[j] < items[best]: best = j total += items[best] del items[max(0, best - 1):best + 2] return totalWhy is
items[j] < items[best]strict<? Because keepingbestunchanged on==preserves the leftmost copy of the minimum weight.This simulation is completely accurate, so it makes a great test oracle on small arrays. However, each round removes at most 3 items, so there are at least
n / 3rounds. In every round, scanning for the minimum inspects the whole remaining list (O(n)) anddelshifts every element after the gap (O(n)). Together that takesO(n²)time — around billions of element operations forn = 100,000.To run fast, we must eliminate both bottlenecks: 1. Stop scanning the whole list to rediscover the minimum every round. 2. Stop shifting elements in memory whenever items are deleted.
Key insight 1: pre-sort `(weight, index)` once
Suppose we pair every item's weight with its original index
(weights[i], i)and sort those pairs once at the beginning. Python compares tuples element by element: smallerweightcomes first, and equal weights are ordered by smalleri.Why does this single sorted list stay valid for the entire simulation, even as items vanish?
- Weights never change. A surviving item keeps its original weight.
- Relative order never changes. Deleting items from a row never swaps two survivors: survivor
ais currently to the left of survivorbif and only ifa < bin the original array. - No item ever comes back. Each round's winner is the minimum
(weight, original_index)among current survivors, which must appear strictly later in the sorted list than the previous round's winner, and every entry skipped in between must already have been deleted.
That means we never need to search again! We simply walk through
sorted_candidatesonce from front to back: - If the item atidxwas already deleted as an earlier winner's neighbor, skip it. - Otherwise, it is guaranteed to be the lightest leftmost survivor right now.Key insight 2: track current neighbors with index arrays
Next, we need a way to find an item's current left and right neighbors and close gaps in
O(1)time instead of shifting a list. A doubly linked list (a chain where each item stores a link to the item currently before it and after it) does exactly that.Because our items already have fixed indices
0 .. n - 1, we do not even need node objects. Two plain integer lists work as links, usingNO_NEIGHBOR = -1to mark the ends of the line:left_idx[i]: index of itemi's current left neighbor, or-1if nothing remains to its left.right_idx[i]: index of itemi's current right neighbor, or-1if nothing remains to its right.is_removed[i]:Trueonce itemihas left the line.
When item
idxis removed, its currentleftandrightneighbors become directly adjacent:Before unlinking idx: left <---> idx <---> right After unlinking idx: left <---------------> right right_idx[left] = right left_idx[right] = leftHere is the
O(1)helper that unlinks one index:NO_NEIGHBOR = -1 def _unlink( idx: int, left_idx: List[int], right_idx: List[int], is_removed: List[bool], ) -> None: """Remove product `idx` from the doubly linked list in O(1) time.""" left = left_idx[idx] right = right_idx[idx] # Stitch `left` and `right` directly to each other so the gap closes in O(1). if left != NO_NEIGHBOR: right_idx[left] = right if right != NO_NEIGHBOR: left_idx[right] = left is_removed[idx] = TrueAssemble the main sweep
Now we combine both ideas inside
sum_minima_with_removals:- Initialize
left_idx[i] = i - 1(or-1ati = 0),right_idx[i] = i + 1(or-1ati = n - 1), andis_removed[i] = False. - Build
sorted_candidatesof(weights[i], i)pairs and sort it. - Sweep through
sorted_candidates. Whenevernot is_removed[idx]:- Add
weighttototal_weight. - Read
left_neighbor = left_idx[idx]andright_neighbor = right_idx[idx]before unlinking anything. - Call
_unlinkonidx, and also onleft_neighborandright_neighborif they are notNO_NEIGHBOR.
- Add
Why is calling
_unlinkthree separate times safe? Unlinkingidxconnectsleft_neighbortoright_neighbor; unlinkingleft_neighborconnects the item left ofleft_neighbortoright_neighbor; and unlinkingright_neighborfinally connects the two outer survivors directly to each other.def sum_minima_with_removals(weights: List[int]) -> int: n = len(weights) if n == 0: return 0 left_idx: List[int] = [] right_idx: List[int] = [] for i in range(n): left_idx.append(i - 1 if i > 0 else NO_NEIGHBOR) right_idx.append(i + 1 if i + 1 < n else NO_NEIGHBOR) is_removed = [False] * n sorted_candidates: List[Tuple[int, int]] = [] for i in range(n): sorted_candidates.append((weights[i], i)) sorted_candidates.sort() total_weight = 0 for weight, idx in sorted_candidates: if is_removed[idx]: continue total_weight += weight left_neighbor = left_idx[idx] right_neighbor = right_idx[idx] _unlink(idx, left_idx, right_idx, is_removed) if left_neighbor != NO_NEIGHBOR: _unlink(left_neighbor, left_idx, right_idx, is_removed) if right_neighbor != NO_NEIGHBOR: _unlink(right_neighbor, left_idx, right_idx, is_removed) return total_weight- Initialize
Trace Example 1 and Example 2 step by step
Example 1:
weights = [8, 3, 6, 2, 9]sorted_candidates = [(2, 3), (3, 1), (6, 2), (8, 0), (9, 4)]Candidate Removed? Action Surviving indices --------- -------- ----------------------------------------------- ----------------- (2, 3) False total = 2; left=2, right=4 -> unlink 3, 2, 4 0 <-> 1 (3, 1) False total = 5; left=0, right=-1 -> unlink 1, 0 (empty) (6, 2) True skip (already removed with 3) (empty) (8, 0) True skip (already removed with 1) (empty) (9, 4) True skip (already removed with 3) (empty)Final
total_weight = 5.Example 2:
weights = [4, 10, 2, 7, 5, 6]sorted_candidates = [(2, 2), (4, 0), (5, 4), (6, 5), (7, 3), (10, 1)]Candidate Removed? Action Surviving indices --------- -------- ----------------------------------------------- ----------------- (2, 2) False total = 2; left=1, right=3 -> unlink 2, 1, 3 0 <-> 4 <-> 5 (4, 0) False total = 6; left=-1, right=4 -> unlink 0, 4 5 (5, 4) True skip (became right neighbor of 0 and was removed) 5 (6, 5) False total = 12; left=-1, right=-1 -> unlink 5 (empty) (7, 3) True skip (empty) (10, 1) True skip (empty)Final
total_weight = 12. Notice that when(4, 0)was picked,right_idx[0]had already been updated to4(weight5), so5was properly removed as a neighbor instead of surviving.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Sentinel index meaning "there is no remaining neighbor on this side of the line". NO_NEIGHBOR = -1 def _unlink( idx: int, left_idx: List[int], right_idx: List[int], is_removed: List[bool], ) -> None: """Remove product `idx` from the doubly linked list in O(1) time.""" left = left_idx[idx] right = right_idx[idx] # Stitch `left` and `right` directly to each other so the gap closes in O(1). if left != NO_NEIGHBOR: right_idx[left] = right if right != NO_NEIGHBOR: left_idx[right] = left is_removed[idx] = True def sum_minima_with_removals(weights: List[int]) -> int: n = len(weights) if n == 0: return 0 # Doubly linked list stored in parallel index arrays: # - left_idx[i]: current surviving neighbor to the left of i, or NO_NEIGHBOR (-1), e.g. [-1, 0, 1, 2] # - right_idx[i]: current surviving neighbor to the right of i, or NO_NEIGHBOR (-1), e.g. [1, 2, 3, -1] # - is_removed[i]: True once product i has been picked or deleted as a neighbor left_idx: List[int] = [] right_idx: List[int] = [] for i in range(n): left_idx.append(i - 1 if i > 0 else NO_NEIGHBOR) right_idx.append(i + 1 if i + 1 < n else NO_NEIGHBOR) is_removed = [False] * n # Phase 1: Pre-sort all products by (weight, original_index). # Deletions never change weights or swap the left-to-right order of survivors, # so "lightest remaining, breaking ties by smallest current index" always equals # the next unremoved entry in this fixed sorted order: e.g. [(2, 3), (3, 1), (6, 2), (8, 0), (9, 4)]. sorted_candidates: List[Tuple[int, int]] = [] for i in range(n): sorted_candidates.append((weights[i], i)) sorted_candidates.sort() # Phase 2: Sweep the sorted order once, skipping products already deleted as neighbors. total_weight = 0 for weight, idx in sorted_candidates: if is_removed[idx]: continue total_weight += weight # Snapshot current neighbors BEFORE unlinking `idx` so we remove the exact # products standing beside `idx` right now. left_neighbor = left_idx[idx] right_neighbor = right_idx[idx] _unlink(idx, left_idx, right_idx, is_removed) if left_neighbor != NO_NEIGHBOR: _unlink(left_neighbor, left_idx, right_idx, is_removed) if right_neighbor != NO_NEIGHBOR: _unlink(right_neighbor, left_idx, right_idx, is_removed) return total_weight✅ Submit now — all tests should pass.
Intuition & how it works
Imagine boxes lined up on a long bench. Each box wears two sticky notes naming the box currently sitting immediately to its left and right, while you hold a pre-printed checklist of all boxes sorted from lightest to heaviest (with ties ordered from left to right). You read down your checklist once: if a box was already cleared off the bench earlier, you skip its line; otherwise you add its weight to your total, lift off that box along with whichever left and right neighbors its sticky notes currently name, and rewrite the sticky notes on the two outer boxes so they now point directly at each other across the gap.
Why does a naive list simulation fall short? Scanning a plain list to find the lightest remaining item takes up to n comparisons per round, and deleting a slice from the middle of a Python list shifts every surviving item to its right. Because each round removes at most three items, there are roughly n / 3 to n / 2 rounds, turning repeated scanning and shifting into quadratic O(n²) work that runs billions of operations on 100,000 items.
We replace those two bottlenecks with two simple structures:
1. A single pre-sorted list of (weight, index) pairs, which never goes stale because removing boxes never changes weights or swaps the left-to-right order of survivors.
2. A doubly linked list — a chain where every item stores links to both its current previous item and its current next item — built out of two integer arrays left_idx and right_idx, using -1 as a sentinel value (a special marker number meaning "no neighbor exists on this side").
Walk through Example 1, weights = [8, 3, 6, 2, 9]:
- Initially, links connect indices 0 <-> 1 <-> 2 <-> 3 <-> 4, and the sorted checklist is [(2, 3), (3, 1), (6, 2), (8, 0), (9, 4)].
- Check (2, 3): still present! Add 2 (total = 2). Index 3 has left neighbor 2 and right neighbor 4, so remove indices 3, 2, and 4. Surviving chain: 0 <-> 1.
- Check (3, 1): still present! Add 3 (total = 5). Index 1 now has left neighbor 0 and no right neighbor (-1), so remove indices 1 and 0. Surviving chain: empty.
- Check (6, 2), (8, 0), and (9, 4): all already marked removed, so skip them and return 5.
Complexity
- Time:
O(n log n), wherenislen(weights). Building the parallel arrays takesO(n), sorting then(weight, index)tuples takesO(n log n), and the single forward sweep visits each tuple once while unlinking each index at most once inO(1)time. - Space:
O(n), becauseleft_idx,right_idx,is_removed, andsorted_candidateseach store one entry per input item.
Edge cases
- Empty input (
[]): returns0immediately without building or sorting anything. - Single item (
[5]): both neighbors areNO_NEIGHBOR(-1), so only the item itself is unlinked and its weight is returned. - Minimum at the first or last position: one neighbor is
-1, so two items leave instead of three (as in Round 2 of Example 1, where[8, 3]picks3at the right end). - Equal weights (
[3, 3, 8]vs[8, 3, 3]): tuple sorting orders equal weights by smaller index, picking the leftmost3first. In[3, 3, 8]that removes[3, 3]and leaves8for a total of11, whereas[8, 3, 3]picks the middle3and removes all three for a total of3. - All weights equal (
[7, 7, 7, 7, 7]): picks index0(removes0, 1), skips1, picks2(removes2, 3), skips3, picks4(removes4), giving7 + 7 + 7 = 21. - Distant elements becoming neighbors (
[4, 10, 2, 7, 5, 6]): removing10, 2, 7links4directly to5, so when4is picked next,5is removed with it (total = 2 + 4 + 6 = 12). - 64-bit sums: for
1 .. 100,000the total is2.5 * 10^9, which overflows a signed 32-bit integer (~2.1 * 10^9). Python integers have arbitrary precision, while C++ or Java solutions must uselong long/long.
Common mistakes
- Checking
i - 1andi + 1instead ofleft_idx[i]andright_idx[i]: once intermediate items are removed, an item's current neighbors are no longer ati - 1andi + 1. - Breaking ties in the wrong direction: sorting only by weight with a reversed or unstable tie-breaker can pick a rightmost equal weight instead of the leftmost one, changing which neighbors survive.
- Forgetting
if is_removed[idx]: continue: without this check, items that were already deleted as neighbors still get added tototal_weightwhen their turn arrives insorted_candidates. - Reading
left_idx[idx]andright_idx[idx]after clearing links: if an unlink helper resetsleft_idx[idx] = -1andright_idx[idx] = -1, reading neighbors after unlinkingidxloses both neighbor indices. Always snapshotleft_neighborandright_neighborbefore unlinking. - Deleting from a Python
listwithpopordel items[...]: every deletion shifts up tonelements in memory, making the overall runtimeO(n²).
Alternative approaches
- Min-heap with lazy deletion: a min-heap is a binary tree structure that pops its smallest item in
O(log n)time, and lazy deletion means leaving stale items inside the heap until they reach the top and discarding them ifis_removed[idx]isTrue. This also runs inO(n log n)time andO(n)space, though sorting a plain list once is shorter and faster in Python because all weights are known up front. - Counting sort when weights have a small max
W: counting sort groups indices into an array ofW + 1buckets indexed directly by weight instead of comparing elements. Appendingifrom0ton - 1keeps each bucket sorted by index automatically, reducing the total runtime toO(n + W).
Follow-up questions
- How would the algorithm and time complexity change if each step deleted up to k surviving neighbors on each side? Keep the exact same pre-sorted candidate list and doubly linked list. When
idxis picked, walkleft_idxup toksteps andright_idxup toksteps, unlinking each item visited along the way. Because every item can be unlinked at most once across the entire run, all neighbor walks combined still do at mostnunlinks (O(n)total), so the overall time remainsO(n log n)regardless ofk. - What adjustments are required if the items sit in a circular ring rather than a straight line? Initialize
left_idx[0] = n - 1andright_idx[n - 1] = 0so the ends wrap around. Two tiny circle cases appear when ≤ 2 items remain: ifleft_neighbor == idx(only 1 item left), skip neighbor unlinks; ifleft_neighbor == right_neighbor(exactly 2 items left, so the same item sits on both sides), unlink that neighbor once instead of twice. - How could you also output the ordered list of chosen items alongside the final weight sum? Append
idx(orweights[idx]) to apickedlist right next tototal_weight += weightinside the loop. Because the sweep processes surviving candidates in exact round order,pickedrecords the round-by-round winners withO(1)extra work per pick.
Follow-up questions
- How would the algorithm and time complexity change if each step deleted up to k surviving neighbors on each side?
- What adjustments are required if the items sit in a circular ring rather than a straight line?
- How could you also output the ordered list of chosen items alongside the final weight sum?
Similar questions
- Count Monthly Devices Above Threshold
- Optimal Worker Count Under Quadratic Merge Overhead
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance