Minimum Remaining Count Under Equal-Tier Merges

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Given an integer array stones where stones[i] denotes the positive integer tier of the i-th stone, you can repeatedly fuse pairs of matching stones. Each fusion removes two stones sharing the exact same tier x and produces one replacement stone of tier x + 1.

Implement the following function:

def magic(stones: list[int]) -> int:

The fusion process follows three rules:

  • Only two stones of identical tier may fuse; two stones with unequal tiers can never be combined directly.
  • Fusions may be carried out any number of times and in any order, and stones produced by earlier fusions can fuse again with other stones of their new tier.
  • Upgraded stones have no maximum tier limit—fusing tiers near 9999 can produce tiers of 10000 or beyond.

Return a single integer: the minimum number of stones that can remain once no further beneficial fusions are made.

Examples

Example 1

Input: stones = [2, 3, 2, 5]
Output: 2

Fuse the two tier-2 stones into one tier-3 stone, then fuse the two tier-3 stones into one tier-4 stone. The remaining stones have tiers 4 and 5, which do not match, leaving 2 stones.

Example 2

Input: stones = [4, 1, 3, 1, 2]
Output: 1

Fusing the pair of tier-1 stones creates a second tier-2 stone, triggering a chain reaction ([2, 2] -> 3, [3, 3] -> 4, [4, 4] -> 5) until a single tier-5 stone is left.

Example 3

Input: stones = [6, 6, 6, 6, 6]
Output: 2

Four of the tier-6 stones form two tier-7 stones, which then combine into one tier-8 stone. Together with the unpaired fifth tier-6 stone, 2 stones (6 and 8) remain.

Constraints

  • 1 <= len(stones) <= 10^5
  • 1 <= stones[i] <= 9999
  • The returned count is an integer between 1 and len(stones), inclusive.

Step-by-step walkthrough

  1. Understand the merging rules

    We are given a list stones of n positive integers (1 <= stones[i] <= 9999), where each integer is a stone's level. Whenever we have two stones of the exact same level x, we can merge them into one stone of level x + 1. Newly merged stones can keep merging with other stones of their new level, and there is no upper limit on how high a stone's level can climb (two level-9999 stones become one level-10000 stone).

    Our goal is to return a single integer: the smallest number of stones that can remain after performing merges optimally.

    Notice right away that a stone's position in stones never affects whether it can merge—only how many stones sit at each level matters.

  2. Key insight: merging stones is binary addition

    At first, it might seem like choosing which pair to merge first could change the final number of stones. Let us check by assigning every level-x stone a "coin value" of 2^x:

    Two stones at level x:   2^x + 2^x = 2 * 2^x = 2^(x + 1)   (one stone at level x + 1!)
    

    Every merge trades two coins of value 2^x for one coin of value 2^(x + 1). That means the total weight S = sum(2^x for x in stones) is an invariant—a quantity that never changes no matter which merges we perform or in what order!

    Now ask: What is the fewest powers of two that can add up to S?

    • As long as any two stones share the same level, we can merge them and reduce the stone count by 1.
    • When no two stones share a level, every remaining level has at most 1 stone—which is the unique binary representation of S (one stone for each 1-bit of S)!

    So the merge order never traps us! Sweeping from the lowest level upward and greedily pairing everything at each level—passing pairs upward as a carry, exactly like elementary-school binary addition—always reaches the unique minimum stone count:

    Level:      2      3      4      5
    Initial:   [2, 2] [3]    []     [5]   (S = 2^2 + 2^2 + 2^3 + 2^5 = 4 + 4 + 8 + 32 = 48)
    Sweep L2:  pair! -> 0 stay, carry 1 stone to level 3
    Sweep L3:  1 initial + 1 carry = 2 -> pair! -> 0 stay, carry 1 stone to level 4
    Sweep L4:  0 initial + 1 carry = 1 -> odd stone stays! (2^4 = 16)
    Sweep L5:  1 initial + 0 carry = 1 -> odd stone stays! (2^5 = 32)
    Result:    2 stones left (16 + 32 = 48)
    
  3. Count starting stones at each level

    First, we count how many stones start at each level using a dictionary counts. Why use a dictionary instead of a fixed array of length 10000? Because cascading carries can climb well past 9999 (for example, 100,000 stones at level 9999 cascade up to level 10015), and a dictionary handles arbitrary levels cleanly without index-out-of-bounds bugs.

    def count_stones_by_level(stones: list[int]) -> Dict[int, int]:
        """Build a frequency map `{level: initial_stone_count}`, e.g. `{2: 2, 3: 1, 5: 1}`."""
        counts: Dict[int, int] = {}
        for level in stones:
            counts[level] = counts.get(level, 0) + 1
        return counts
    
  4. Sweep from lowest level upward with a carry

    Now we sweep level upward starting from min(counts) with carry = 0:

    1. Combine the initial stones at level with the carry arriving from level - 1: total_at_level = counts.get(level, 0) + carry.
    2. If total_at_level is odd, total_at_level % 2 == 1 stone has no partner. Because every lower level has already been processed, no future merge can ever create another stone at level—so that 1 stone stays behind permanently (remaining_stones += total_at_level % 2).
    3. Every pair merges into one stone one level higher: carry = total_at_level // 2.

    Watch the while condition carefully: we must keep looping while level <= max_input_level or carry > 0. Stopping at max_input_level would silently throw away carried stones above the highest input level (turning [9999, 9999] into 0 instead of 1!). Above max_input_level, counts.get(level, 0) is 0, so carry halves on every step and reaches 0 in at most log2(n) (<= 17) extra steps.

    def sweep_with_carry(counts: Dict[int, int]) -> int:
        """Merge equal-level pairs from the lowest level upward; return remaining stone count."""
        remaining_stones = 0
        carry = 0  # stones created at `level - 1` that just merged up into `level`
    
        level = min(counts)
        max_input_level = max(counts)
    
        # Keep sweeping past `max_input_level` as long as `carry > 0`, because merged
        # stones can cascade to levels above 9999 (e.g., [9999, 9999] -> one level-10000 stone).
        while level <= max_input_level or carry > 0:
            total_at_level = counts.get(level, 0) + carry
    
            # An odd stone out has no partner and nothing below can ever create another
            # stone at `level`, so `total_at_level % 2` (0 or 1) stays behind permanently.
            remaining_stones += total_at_level % 2
    
            # Every pair of stones at `level` merges into one stone at `level + 1`.
            carry = total_at_level // 2
            level += 1
    
        return remaining_stones
    
    
    def magic(stones: list[int]) -> int:
        if not stones:
            return 0
        counts = count_stones_by_level(stones)
        return sweep_with_carry(counts)
    
  5. Trace Example 1 and Example 3

    First, trace Example 1 with stones = [2, 3, 2, 5] (counts = {2: 2, 3: 1, 5: 1}, max_input_level = 5):

    level | counts[level] | carry in | total_at_level | stays (% 2) | carry out (// 2)
    ------+---------------+----------+----------------+-------------+-----------------
      2   |       2       |    0     |       2        |      0      |        1
      3   |       1       |    1     |       2        |      0      |        1
      4   |       0       |    1     |       1        |      1      |        0
      5   |       1       |    0     |       1        |      1      |        0
    Total remaining_stones = 0 + 0 + 1 + 1 = 2
    

    Now trace Example 3 with stones = [6, 6, 6, 6, 6] (counts = {6: 5}, max_input_level = 6) to see carries continue above max_input_level:

    level | counts[level] | carry in | total_at_level | stays (% 2) | carry out (// 2)
    ------+---------------+----------+----------------+-------------+-----------------
      6   |       5       |    0     |       5        |      1      |        2
      7   |       0       |    2     |       2        |      0      |        1
      8   |       0       |    1     |       1        |      1      |        0
    Total remaining_stones = 1 + 0 + 1 = 2 (one stone at level 6 and one stone at level 8!)
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_stones_by_level(stones: list[int]) -> Dict[int, int]:
        """Build a frequency map `{level: initial_stone_count}`, e.g. `{2: 2, 3: 1, 5: 1}`."""
        counts: Dict[int, int] = {}
        for level in stones:
            counts[level] = counts.get(level, 0) + 1
        return counts
    
    
    def sweep_with_carry(counts: Dict[int, int]) -> int:
        """Merge equal-level pairs from the lowest level upward; return remaining stone count."""
        remaining_stones = 0
        carry = 0  # stones created at `level - 1` that just merged up into `level`
    
        level = min(counts)
        max_input_level = max(counts)
    
        # Keep sweeping past `max_input_level` as long as `carry > 0`, because merged
        # stones can cascade to levels above 9999 (e.g., [9999, 9999] -> one level-10000 stone).
        while level <= max_input_level or carry > 0:
            total_at_level = counts.get(level, 0) + carry
    
            # An odd stone out has no partner and nothing below can ever create another
            # stone at `level`, so `total_at_level % 2` (0 or 1) stays behind permanently.
            remaining_stones += total_at_level % 2
    
            # Every pair of stones at `level` merges into one stone at `level + 1`.
            carry = total_at_level // 2
            level += 1
    
        return remaining_stones
    
    
    def magic(stones: list[int]) -> int:
        if not stones:
            return 0
        counts = count_stones_by_level(stones)
        return sweep_with_carry(counts)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine every stone of level x is a coin worth 2^x points (2 points for level 1, 4 points for level 2, 8 points for level 3, and so on). Merging two level-x stones into one level-(x + 1) stone is just walking up to a cashier and exchanging two 2^x-point coins for one 2^(x + 1)-point coin (4 + 4 = 8). Notice that your total point value never changes—in math and engineering, a quantity that stays constant across every allowed move is called an invariant. And when can you no longer exchange any coins? Exactly when you hold at most one coin of each power-of-two denomination, which is the unique binary representation of your total value! That means you never have to worry about picking the "wrong" merge order: sweeping from the smallest denomination upward and trading every pair of matching coins into one coin of the next denomination—passing pairs upward as a carry—is guaranteed to leave the fewest coins possible (one coin for each 1-bit in the binary sum).

Why do naive approaches fail? Trying every possible merge order recursively explores an exponential number of intermediate piles and times out past a dozen stones, while scanning a list to find and merge one pair at a time takes O(n) per merge and O(n^2) overall on 100,000 stones. Even worse, pairing only the original input stones in a single pass misses cascading merges where newly created stones pair up again.

Walk through stones = [4, 1, 3, 1, 2] (Example 2):

  1. Count initial stones per level: {1: 2, 2: 1, 3: 1, 4: 1}.
  2. Level 1: 2 stones pair into carry = 1 stone for level 2 (0 stay behind).
  3. Level 2: 1 initial + 1 carry = 2 stones, pairing into carry = 1 for level 3 (0 stay).
  4. Level 3: 1 initial + 1 carry = 2 stones, pairing into carry = 1 for level 4 (0 stay).
  5. Level 4: 1 initial + 1 carry = 2 stones, pairing into carry = 1 for level 5 (0 stay).
  6. Level 5: 0 initial + 1 carry = 1 odd stone, which stays (carry = 0). Total remaining: 1.

Complexity

Let n be len(stones), d be the number of distinct levels in stones, and L = max(stones) - min(stones) + 1 be the span between the smallest and largest input levels (L <= 9999).

  • Time: O(n + L + log n). Building the counts dictionary visits each of the n stones once with O(1) average dictionary updates. The upward sweep then executes O(1) arithmetic at each integer level from min(stones) through max(stones) (L steps), plus at most floor(log2(n)) + 1 (<= 17 for n = 10^5) extra steps above max(stones) because carry halves on every step once no more initial stones exist. With n <= 10^5 and L <= 9999, the entire function performs roughly 110,000 tiny operations.
  • Space: O(d). The counts dictionary stores one entry per distinct input level (d <= min(n, 9999)), while the sweep uses only a few integer variables (remaining_stones, carry, level).

Edge cases

  • Single stone ([7]): total_at_level = 1, so 1 % 2 = 1 stone stays and carry = 0; returns 1.
  • All distinct levels ([1, 3, 5, 9999]): Stones of different levels can never merge (even adjacent levels 1 and 2), so all 4 stones remain.
  • Odd count at a level ([6, 6, 6, 6, 6]): Level 6 leaves 5 % 2 = 1 stone behind and carries 5 // 2 = 2 stones to level 7, which merge into 1 stone at level 8, leaving 2 stones total.
  • Power-of-two identical stones ([4] * 8): Collapses 8 -> 4 -> 2 -> 1, returning 1.
  • Merging above 9999 ([9999, 9999]): Level 9999 sets carry = 1, and while ... or carry > 0 continues to level 10000 where that carried stone is counted, returning 1.
  • Maximum input ([9999] * 100000): Since 100,000 = 65,536 + 32,768 + 1,024 + 512 + 128 + 32 = 2^16 + 2^15 + 2^10 + 2^9 + 2^7 + 2^5 has six 1-bits, carries climb up to level 9999 + 16 = 10015 and leave 6 stones.

Common mistakes

  • Stopping the loop at max(stones) (while level <= max_input_level): Any carry produced at the highest input level is forgotten, causing [9999, 9999] to return 0 instead of 1!
  • Sweeping from highest level down to lowest: Processing level 3 before level 2 misses the carried stone that [2, 2] pushes up into level 3, returning 3 instead of 2 on [2, 3, 2, 5].
  • Allocating a fixed array of size 10000 or 10001: Input levels stop at 9999, but merged stones do not! With 100,000 < 2^17 stones at level 9999, the total weight is 100,000 * 2^9999 < 2^10016, reaching level 10015—so a 0-indexed array would need at least 10016 slots not to crash with IndexError.
  • Simulating merges by repeatedly scanning or sorting stones: Up to n - 1 merges can happen ([1] * 100000), so spending O(n) per merge takes O(n^2) time.

Alternative approaches

  • Arbitrary-precision bit count (popcount): Because the answer equals the popcount (the number of 1-bits in the binary representation of an integer) of S = sum(2^x for x in stones), Python's arbitrary-precision integers can compute bin(sum(1 << level for level in stones)).count("1"). Be cautious on large inputs: adding n = 10^5 integers that are 10,000 bits wide copies ~1,250 bytes on every +, costing O(n * max_level) bit operations (~10^9 bit ops on [1] + [9999] * 100000), whereas counting in a dictionary first and sweeping carry touches each stone in O(1) word operations!
  • Min-heap simulation: Push all stone levels into a min-heap (heapq). Repeatedly pop the smallest stone a; if the heap is non-empty and its top equals a, pop the partner and push a + 1, otherwise increment remaining_stones. This runs in O(n log n) time and works even for huge sparse levels without sweeping empty levels, though for stones[i] <= 9999 the linear dictionary sweep is faster and simpler.

Follow-up questions

  • What change is needed if you must output the remaining stone levels in ascending order rather than just how many remain? Inside sweep_with_carry, whenever total_at_level % 2 == 1, append level to a result_levels list instead of adding 1 to remaining_stones. Because level strictly increases by 1 on each iteration, result_levels is already sorted in ascending order with zero extra time complexity.
  • How would you adapt the algorithm if initial levels could be as large as 10^18 while len(stones) stays up to 10^5? Stepping level += 1 across an empty gap like [1, 10^18] would loop 10^18 times and hang! Fix it in O(n + d log d) time by iterating over sorted(counts.keys()): before each next_level, propagate carry one level at a time only while carry > 0 and level < next_level (at most log2(n) <= 17 steps before carry hits 0), and as soon as carry == 0, jump level = next_level directly in O(1) time over any billion-level empty gap!
  • Suppose k matching stones (k >= 2) fuse into a single stone of level x + 1; how does the invariant and sweep change? Give each level-x stone weight k^x so k * k^x = k^(x + 1) preserves the total weight S in base k. In sweep_with_carry, simply replace % 2 and // 2 with remaining_stones += total_at_level % k and carry = total_at_level // k, which computes the sum of the base-k digits of S.
  • If new stones arrive one at a time in a stream, how can you maintain the minimum remaining count in O(1) amortized time per arrival? Maintain a boolean set (or 0/1 dictionary) present holding the currently occupied levels, whose len(present) is always the live answer. Adding a stone at level works exactly like adding 1 at bit level of a binary number: while level in present, remove level from present and increment level += 1, then add the final level to present. Each arrival adds at most one element to present and each remove consumes a previously added element, so m arrivals perform at most m removals in total—amortized O(1) time per stone!

Follow-up questions

Similar questions

More Elevenlabs interview questions

All 3 Elevenlabs questions →