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
9999can produce tiers of10000or 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^51 <= stones[i] <= 9999- The returned count is an integer between
1andlen(stones), inclusive.
Step-by-step walkthrough
Understand the merging rules
We are given a list
stonesofnpositive integers (1 <= stones[i] <= 9999), where each integer is a stone's level. Whenever we have two stones of the exact same levelx, we can merge them into one stone of levelx + 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-9999stones become one level-10000stone).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
stonesnever affects whether it can merge—only how many stones sit at each level matters.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-
xstone a "coin value" of2^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^xfor one coin of value2^(x + 1). That means the total weightS = 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
1stone—which is the unique binary representation ofS(one stone for each1-bit ofS)!
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)- As long as any two stones share the same level, we can merge them and reduce the stone count by
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 length10000? Because cascading carries can climb well past9999(for example,100,000stones at level9999cascade up to level10015), 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 countsSweep from lowest level upward with a carry
Now we sweep
levelupward starting frommin(counts)withcarry = 0:- Combine the initial stones at
levelwith thecarryarriving fromlevel - 1:total_at_level = counts.get(level, 0) + carry. - If
total_at_levelis odd,total_at_level % 2 == 1stone has no partner. Because every lower level has already been processed, no future merge can ever create another stone atlevel—so that1stone stays behind permanently (remaining_stones += total_at_level % 2). - Every pair merges into one stone one level higher:
carry = total_at_level // 2.
Watch the
whilecondition carefully: we must keep looping whilelevel <= max_input_level or carry > 0. Stopping atmax_input_levelwould silently throw away carried stones above the highest input level (turning[9999, 9999]into0instead of1!). Abovemax_input_level,counts.get(level, 0)is0, socarryhalves on every step and reaches0in at mostlog2(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)- Combine the initial stones at
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 = 2Now trace Example 3 with
stones = [6, 6, 6, 6, 6](counts = {6: 5},max_input_level = 6) to see carries continue abovemax_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!)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):
- Count initial stones per level:
{1: 2, 2: 1, 3: 1, 4: 1}. - Level 1:
2stones pair intocarry = 1stone for level 2 (0stay behind). - Level 2:
1initial +1carry =2stones, pairing intocarry = 1for level 3 (0stay). - Level 3:
1initial +1carry =2stones, pairing intocarry = 1for level 4 (0stay). - Level 4:
1initial +1carry =2stones, pairing intocarry = 1for level 5 (0stay). - Level 5:
0initial +1carry =1odd 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
countsdictionary visits each of thenstones once withO(1)average dictionary updates. The upward sweep then executesO(1)arithmetic at each integer level frommin(stones)throughmax(stones)(Lsteps), plus at mostfloor(log2(n)) + 1(<= 17forn = 10^5) extra steps abovemax(stones)becausecarryhalves on every step once no more initial stones exist. Withn <= 10^5andL <= 9999, the entire function performs roughly110,000tiny operations. - Space: O(d). The
countsdictionary 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, so1 % 2 = 1stone stays andcarry = 0; returns1. - All distinct levels (
[1, 3, 5, 9999]): Stones of different levels can never merge (even adjacent levels1and2), so all4stones remain. - Odd count at a level (
[6, 6, 6, 6, 6]): Level 6 leaves5 % 2 = 1stone behind and carries5 // 2 = 2stones to level 7, which merge into1stone at level 8, leaving2stones total. - Power-of-two identical stones (
[4] * 8): Collapses8 -> 4 -> 2 -> 1, returning1. - Merging above
9999([9999, 9999]): Level9999setscarry = 1, andwhile ... or carry > 0continues to level10000where that carried stone is counted, returning1. - Maximum input (
[9999] * 100000): Since100,000 = 65,536 + 32,768 + 1,024 + 512 + 128 + 32 = 2^16 + 2^15 + 2^10 + 2^9 + 2^7 + 2^5has six1-bits, carries climb up to level9999 + 16 = 10015and leave6stones.
Common mistakes
- Stopping the loop at
max(stones)(while level <= max_input_level): Anycarryproduced at the highest input level is forgotten, causing[9999, 9999]to return0instead of1! - Sweeping from highest level down to lowest: Processing level
3before level2misses the carried stone that[2, 2]pushes up into level3, returning3instead of2on[2, 3, 2, 5]. - Allocating a fixed array of size
10000or10001: Input levels stop at9999, but merged stones do not! With100,000 < 2^17stones at level9999, the total weight is100,000 * 2^9999 < 2^10016, reaching level10015—so a 0-indexed array would need at least10016slots not to crash withIndexError. - Simulating merges by repeatedly scanning or sorting
stones: Up ton - 1merges can happen ([1] * 100000), so spendingO(n)per merge takesO(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) ofS = sum(2^x for x in stones), Python's arbitrary-precision integers can computebin(sum(1 << level for level in stones)).count("1"). Be cautious on large inputs: addingn = 10^5integers that are10,000bits wide copies ~1,250bytes on every+, costingO(n * max_level)bit operations (~10^9bit ops on[1] + [9999] * 100000), whereas counting in a dictionary first and sweepingcarrytouches each stone inO(1)word operations! - Min-heap simulation: Push all stone levels into a min-heap (
heapq). Repeatedly pop the smallest stonea; if the heap is non-empty and its top equalsa, pop the partner and pusha + 1, otherwise incrementremaining_stones. This runs inO(n log n)time and works even for huge sparse levels without sweeping empty levels, though forstones[i] <= 9999the 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, whenevertotal_at_level % 2 == 1, appendlevelto aresult_levelslist instead of adding1toremaining_stones. Becauselevelstrictly increases by1on each iteration,result_levelsis 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 += 1across an empty gap like[1, 10^18]would loop10^18times and hang! Fix it inO(n + d log d)time by iterating oversorted(counts.keys()): before eachnext_level, propagatecarryone level at a time only whilecarry > 0 and level < next_level(at mostlog2(n) <= 17steps beforecarryhits0), and as soon ascarry == 0, jumplevel = next_leveldirectly inO(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-
xstone weightk^xsok * k^x = k^(x + 1)preserves the total weightSin basek. Insweep_with_carry, simply replace% 2and// 2withremaining_stones += total_at_level % kandcarry = total_at_level // k, which computes the sum of the base-kdigits ofS. - 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/1dictionary)presentholding the currently occupied levels, whoselen(present)is always the live answer. Adding a stone atlevelworks exactly like adding1at bitlevelof a binary number: whilelevel in present, removelevelfrompresentand incrementlevel += 1, then add the finalleveltopresent. Each arrival adds at most one element topresentand eachremoveconsumes a previously added element, somarrivals perform at mostmremovals in total—amortizedO(1)time per stone!
Follow-up questions
- What change is needed if you must output the remaining stone levels in ascending order rather than just how many remain?
- How would you adapt the algorithm if initial levels could be as large as 10^18 while len(stones) stays up to 10^5?
- Suppose k matching stones (k >= 2) fuse into a single stone of level x + 1; how does the invariant and sweep change?
- 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?
Similar questions
- Minimum-Cost Daily Color Schedule
- Next Greater Integer With Disjoint Digits
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance