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:

  1. Locate the minimum weight among all items still present. Whenever multiple surviving items share that minimum weight, select the leftmost one (lowest current position).
  2. Add the selected item's weight to the accumulated total.
  3. 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^5
  • 1 <= weights[i] <= 10^9

Step-by-step walkthrough

  1. 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:

    1. Choose the lightest remaining item. If several remaining items tie for the lightest weight, choose the leftmost one (the smallest current index).
    2. Add that item's weight to our running total.
    3. 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 left 3 removes [3, 3] and leaves [8], giving 3 + 8 = 11. Picking the right 3 first would have removed all three items at once and given 3.
    • 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.
    
  2. 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 total
    

    Why is items[j] < items[best] strict <? Because keeping best unchanged 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 / 3 rounds. In every round, scanning for the minimum inspects the whole remaining list (O(n)) and del shifts every element after the gap (O(n)). Together that takes O(n²) time — around billions of element operations for n = 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.

  3. 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: smaller weight comes first, and equal weights are ordered by smaller i.

    Why does this single sorted list stay valid for the entire simulation, even as items vanish?

    1. Weights never change. A surviving item keeps its original weight.
    2. Relative order never changes. Deleting items from a row never swaps two survivors: survivor a is currently to the left of survivor b if and only if a < b in the original array.
    3. 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_candidates once from front to back: - If the item at idx was already deleted as an earlier winner's neighbor, skip it. - Otherwise, it is guaranteed to be the lightest leftmost survivor right now.

  4. 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, using NO_NEIGHBOR = -1 to mark the ends of the line:

    • left_idx[i]: index of item i's current left neighbor, or -1 if nothing remains to its left.
    • right_idx[i]: index of item i's current right neighbor, or -1 if nothing remains to its right.
    • is_removed[i]: True once item i has left the line.

    When item idx is removed, its current left and right neighbors become directly adjacent:

    Before unlinking idx:   left  <--->  idx  <--->  right
    After unlinking idx:    left  <--------------->  right
                            right_idx[left] = right
                            left_idx[right] = left
    

    Here 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] = True
    
  5. Assemble the main sweep

    Now we combine both ideas inside sum_minima_with_removals:

    1. Initialize left_idx[i] = i - 1 (or -1 at i = 0), right_idx[i] = i + 1 (or -1 at i = n - 1), and is_removed[i] = False.
    2. Build sorted_candidates of (weights[i], i) pairs and sort it.
    3. Sweep through sorted_candidates. Whenever not is_removed[idx]:
      • Add weight to total_weight.
      • Read left_neighbor = left_idx[idx] and right_neighbor = right_idx[idx] before unlinking anything.
      • Call _unlink on idx, and also on left_neighbor and right_neighbor if they are not NO_NEIGHBOR.

    Why is calling _unlink three separate times safe? Unlinking idx connects left_neighbor to right_neighbor; unlinking left_neighbor connects the item left of left_neighbor to right_neighbor; and unlinking right_neighbor finally 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
    
  6. 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 to 4 (weight 5), so 5 was properly removed as a neighbor instead of surviving.

  7. 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), where n is len(weights). Building the parallel arrays takes O(n), sorting the n (weight, index) tuples takes O(n log n), and the single forward sweep visits each tuple once while unlinking each index at most once in O(1) time.
  • Space: O(n), because left_idx, right_idx, is_removed, and sorted_candidates each store one entry per input item.

Edge cases

  • Empty input ([]): returns 0 immediately without building or sorting anything.
  • Single item ([5]): both neighbors are NO_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] picks 3 at the right end).
  • Equal weights ([3, 3, 8] vs [8, 3, 3]): tuple sorting orders equal weights by smaller index, picking the leftmost 3 first. In [3, 3, 8] that removes [3, 3] and leaves 8 for a total of 11, whereas [8, 3, 3] picks the middle 3 and removes all three for a total of 3.
  • All weights equal ([7, 7, 7, 7, 7]): picks index 0 (removes 0, 1), skips 1, picks 2 (removes 2, 3), skips 3, picks 4 (removes 4), giving 7 + 7 + 7 = 21.
  • Distant elements becoming neighbors ([4, 10, 2, 7, 5, 6]): removing 10, 2, 7 links 4 directly to 5, so when 4 is picked next, 5 is removed with it (total = 2 + 4 + 6 = 12).
  • 64-bit sums: for 1 .. 100,000 the total is 2.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 use long long / long.

Common mistakes

  • Checking i - 1 and i + 1 instead of left_idx[i] and right_idx[i]: once intermediate items are removed, an item's current neighbors are no longer at i - 1 and i + 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 to total_weight when their turn arrives in sorted_candidates.
  • Reading left_idx[idx] and right_idx[idx] after clearing links: if an unlink helper resets left_idx[idx] = -1 and right_idx[idx] = -1, reading neighbors after unlinking idx loses both neighbor indices. Always snapshot left_neighbor and right_neighbor before unlinking.
  • Deleting from a Python list with pop or del items[...]: every deletion shifts up to n elements in memory, making the overall runtime O(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 if is_removed[idx] is True. This also runs in O(n log n) time and O(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 of W + 1 buckets indexed directly by weight instead of comparing elements. Appending i from 0 to n - 1 keeps each bucket sorted by index automatically, reducing the total runtime to O(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 idx is picked, walk left_idx up to k steps and right_idx up to k steps, 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 most n unlinks (O(n) total), so the overall time remains O(n log n) regardless of k.
  • What adjustments are required if the items sit in a circular ring rather than a straight line? Initialize left_idx[0] = n - 1 and right_idx[n - 1] = 0 so the ends wrap around. Two tiny circle cases appear when ≤ 2 items remain: if left_neighbor == idx (only 1 item left), skip neighbor unlinks; if left_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 (or weights[idx]) to a picked list right next to total_weight += weight inside the loop. Because the sweep processes surviving candidates in exact round order, picked records the round-by-round winners with O(1) extra work per pick.

Follow-up questions

Similar questions

More Kneron interview questions

All 3 Kneron questions →