Exponential Patch Growth and Coin Counts
Medium · Statistics & Math · Software Engineer · Online Assessment
Problem Statement
Implement solve_lily_pad_and_coins(cover_day, first_rate, second_rate, coin_count, total_cents) to solve three linked quantitative subproblems — two involving discrete compound area expansion and one involving a two-denomination coin split — and return all results in a single dictionary.
def solve_lily_pad_and_coins(
cover_day: int,
first_rate: int,
second_rate: int,
coin_count: int,
total_cents: int,
) -> Dict[str, int]:
Growth & Coin Rules
- Quarter-capacity milestone (
"quarter_covered_day"):- A water-plant colony starts on Day
1with an area of1unit. - Between each Day
dand Dayd + 1, its area multiplies by the integer factorfirst_rate, so on Dayd(d >= 1) its area isfirst_rate ** (d - 1)units. - On Day
cover_day, this first colony reaches full basin capacity (first_rate ** (cover_day - 1)units). - Return the earliest integer day (
>= 1) on which the first colony covers at least1/4of full basin capacity.
- A water-plant colony starts on Day
- Alternative growth schedule (
"second_patch_full_day"):- A separate colony also starts on Day
1at1unit of area, multiplying bysecond_ratebetween consecutive days (second_rate ** (d - 1)units on Dayd). - Return the earliest integer day (
>= 1) on which this second colony alone covers at least100%of full basin capacity, or-1if it never reaches full capacity.
- A separate colony also starts on Day
- Two-coin breakdown (
"nickels"and"dimes"):- A pouch holds
coin_countcoins consisting solely of 5-cent nickels and 10-cent dimes whose combined worth equalstotal_centscents. - Return the non-negative integer counts for
"nickels"and"dimes". If no non-negative integer pair satisfies bothcoin_countandtotal_cents, set both"nickels"and"dimes"to-1.
- A pouch holds
- Input validation:
- Raise
ValueErrorifcover_day < 1,first_rate < 1,second_rate < 1,coin_count < 0, ortotal_cents < 0.
- Raise
Examples
Example 1
Input: cover_day = 30, first_rate = 2, second_rate = 3, coin_count = 24, total_cents = 185
Output: {'quarter_covered_day': 28, 'second_patch_full_day': 20, 'nickels': 11, 'dimes': 13}
- Quarter capacity: Doubling daily reaches
100%on Day30, so coverage was1/2on Day29and1/4on Day28. - Second colony: Full capacity is
2^29 = 536,870,912Day-1 units. Tripling from1gives3^18 = 387,420,489on Day19(short) and3^19 = 1,162,261,467on Day20(full). - Coins:
11nickels (55cents) plus13dimes (130cents) use24coins and sum to185cents.
Example 2
Input: cover_day = 7, first_rate = 2, second_rate = 4, coin_count = 16, total_cents = 110
Output: {'quarter_covered_day': 5, 'second_patch_full_day': 4, 'nickels': 10, 'dimes': 6}
- Quarter capacity: Rewinding two doublings from Day
7(1 -> 1/2 -> 1/4) lands on Day5. - Second colony: Full capacity is
2^6 = 64units; quadrupling reaches4^3 = 64after3daily transitions, which is Day4. - Coins:
10nickels (50cents) and6dimes (60cents) total16coins worth110cents.
Example 3
Input: cover_day = 15, first_rate = 3, second_rate = 1, coin_count = 8, total_cents = 95
Output: {'quarter_covered_day': 14, 'second_patch_full_day': -1, 'nickels': -1, 'dimes': -1}
- Quarter capacity: With factor
3, coverage is1/3 >= 1/4on Day14and1/9 < 1/4on Day13, so Day14is the earliest day at or above1/4. - Second colony: A factor-
1colony stays at1unit forever and never reaches3^14units (-1). - Coins: Eight coins can be worth at most
8 * 10 = 80cents, so95cents is unreachable (-1, -1).
Constraints
cover_day >= 1,first_rate >= 1,second_rate >= 1(raiseValueErrorotherwise)coin_count >= 0,total_cents >= 0(raiseValueErrorotherwise)- Typical valid inputs satisfy
1 <= cover_day <= 10^4,1 <= first_rate, second_rate <= 10,0 <= coin_count <= 10^6, and0 <= total_cents <= 10^7 - Arithmetic on capacities must remain exact across large exponents (floating-point logarithms can misround exact integer powers)
Step-by-step walkthrough
Understand the three tasks and the day-numbering model
A single call to
solve_lily_pad_and_coinsanswers three quantitative puzzles and packs them into one dictionary:Key Meaning ----------------------- --------------------------------------------------------------------- "quarter_covered_day" Task 1: first day the first patch covers >= 1/4 of the pond "second_patch_full_day" Task 2: first day the second patch alone covers >= 100% of the pond "nickels" Task 3: number of 5-cent nickels (or -1 if impossible) "dimes" Task 3: number of 10-cent dimes (or -1 if impossible)Before writing a single formula, lock down when growth happens so we never suffer an off-by-one error:
- Day 1 is the starting size of a patch (
1unit). - Growth happens once between consecutive days: moving from Day
dto Dayd + 1multiplies the patch size by itsrate. - Therefore, on Day
d, a patch has multipliedd - 1times (notdtimes!), so its size israte ** (d - 1)units, and day numbers never go below1.
When
first_rateis2or4, the pond hits exact1/4coverage on an integer day (2days back or1day back). For a general integer rate like3(where coverage goes1/9 -> 1/3 -> 1), no day is exact1/4, so we report the first day with at least1/4coverage (which equals the exact quarter-day whenever one exists). Similarly, Task 2 returns-1if the second patch never fills the pond, and Task 3 returns-1for both coins if no non-negative integer split exists.- Day 1 is the starting size of a patch (
Task 1: Step backward from the full day
When a colony doubles every day and fills the basin on Day
30, a hasty guess might suggest "a quarter of30is around Day7or8." That confuses multiplying by2with adding a constant amount! Running the timeline backward makes the answer obvious:Day 28 Day 29 Day 30 [ 1/4 full ] --x2--> [ 1/2 full ] --x2--> [ 1/1 full ]Each step backward divides the pond coverage by
rate. To avoid floating-point decimals completely, track the denominatorinverse_fractionso that onday, the pond is1 / inverse_fractioncovered:- On
cover_day,inverse_fraction = 1(1/1full). - Stepping back one day would make the coverage
1 / (inverse_fraction * rate). - That earlier day is still at least
1/4covered if and only if1 / (inverse_fraction * rate) >= 1 / 4, which cross-multiplies cleanly in integers toinverse_fraction * rate <= 4. - Also stop if
day == 1(the patch did not exist on Day0), and handlerate == 1immediately (a non-growing patch that is full oncover_daywas already100%full on Day1).
def find_quarter_covered_day(cover_day: int, rate: int) -> int: """Return the earliest day (>= 1) on which the patch covers at least 1/4 of the pond.""" if rate == 1: # A rate-1 patch never changes size, so it already covered 100% (>= 1/4) on Day 1. return 1 day = cover_day # inverse_fraction tracks the denominator of coverage: on `day`, pond is (1 / inverse_fraction) full. inverse_fraction = 1 # Step backward while day > 1 and the previous day still has >= 1/4 coverage: # 1 / (inverse_fraction * rate) >= 1 / 4 is equivalent to inverse_fraction * rate <= 4. while day > 1 and inverse_fraction * rate <= 4: inverse_fraction *= rate day -= 1 return day- On
Task 2: Measure the pond in Day-1 patch units (without float logs)
Both patches start at the exact same size on Day
1. Call that starting size1unit!- Between Day
1andcover_day, the first patch multipliescover_day - 1times, so the pond's total capacity ispond_capacity = first_rate ** (cover_day - 1)units. - On Day
n, the second patch has multipliedn - 1times, so its size issecond_rate ** (n - 1)units. - We want the smallest day
n >= 1such thatsecond_rate ** (n - 1) >= pond_capacity.
Why shouldn't we just write
1 + math.ceil(math.log(pond_capacity, second_rate))? Because floating-point logarithms suffer from tiny rounding errors at exact powers! In Python,math.log(125, 5)evaluates to3.0000000000000004, somath.ceil(...)rounds it up to4instead of3— reporting Day5when5^3 = 125was already full on Day4!Python's integers have unlimited precision, so we can start
current_size = 1onday = 1and multiply bysecond_rateuntilcurrent_size >= pond_capacitywith zero rounding error. Just guardsecond_rate == 1first so a non-growing second patch returns-1(unlesspond_capacity == 1, where Day1is already full) instead of looping forever.def find_second_patch_full_day(cover_day: int, first_rate: int, second_rate: int) -> int: """Return the first day on which the second patch covers the whole pond, or -1 if never.""" # Measure capacity in exact Day-1 patch units: first patch grows (cover_day - 1) times to fill pond. pond_capacity = first_rate ** (cover_day - 1) if second_rate == 1: # Without growth, the second patch stays at 1 unit forever; it only fills a size-1 pond. return 1 if pond_capacity <= 1 else -1 current_size = 1 day = 1 # Multiply exact integers rather than taking float logarithms (math.log(125, 5) > 3.0 in IEEE-754). while current_size < pond_capacity: current_size *= second_rate day += 1 return day- Between Day
Task 3: Solve the coin equations using the nickel-to-dime swap trick
Work in integer cents (
5cents per nickel,10cents per dime) rather than floating-point dollars (0.05and0.10) so decimal rounding never touches our math. Withnickelsanddimesas our two unknowns:Equation 1 (coin count): nickels + dimes = coin_count Equation 2 (total value): 5 * nickels + 10 * dimes = total_centsSubstitute
nickels = coin_count - dimesfrom Equation 1 into Equation 2:5 * (coin_count - dimes) + 10 * dimes = total_cents 5 * coin_count + 5 * dimes = total_cents 5 * dimes = total_cents - 5 * coin_count dimes = (total_cents - 5 * coin_count) / 5There is also a great mental picture for that exact formula: imagine laying
coin_countnickels on the table first (5 * coin_countcents). Every time you swap1nickel for1dime, the total number of coins stayscoin_count, and the total value goes up by+5cents!Start: 24 nickels, 0 dimes -> 24 * 5c = 120c (need 185c - 120c = +65c more) Each swap (1 nickel -> 1 dime) adds +5c (65c / 5c = 13 swaps) End : 11 nickels, 13 dimes -> 55c + 130c = 185cFor the solution to be valid non-negative integers, three checks must pass: 1.
extra_cents >= 0(otherwise even all nickels exceedtotal_cents). 2.extra_cents % 5 == 0(otherwise we would need a fractional coin). 3.nickels = coin_count - dimes >= 0(otherwise even all dimes fall short oftotal_cents).def solve_coins(coin_count: int, total_cents: int) -> Tuple[int, int]: """Return (nickels, dimes) for the given count and value in cents, or (-1, -1) if impossible.""" # Start with all nickels (5c each); swapping 1 nickel for 1 dime keeps count fixed and adds 5c. all_nickels_cents = 5 * coin_count extra_cents = total_cents - all_nickels_cents # extra_cents must be non-negative and a multiple of 5c to represent whole nickel-to-dime swaps. if extra_cents < 0 or extra_cents % 5 != 0: return -1, -1 dimes = extra_cents // 5 nickels = coin_count - dimes if nickels < 0: # Even making all coins dimes (10 * coin_count cents) cannot reach total_cents. return -1, -1 return nickels, dimesWalk through Example 1 end to end
Let's trace
solve_lily_pad_and_coins(30, 2, 3, 24, 185):Task 1 (cover_day = 30, first_rate = 2): day = 30, inverse_fraction = 1 -> 1 * 2 <= 4 -> day = 29, inverse_fraction = 2 day = 29, inverse_fraction = 2 -> 2 * 2 <= 4 -> day = 28, inverse_fraction = 4 day = 28, inverse_fraction = 4 -> 4 * 2 = 8 > 4 -> stop! quarter_covered_day = 28 Task 2 (cover_day = 30, first_rate = 2, second_rate = 3): pond_capacity = 2 ** 29 = 536,870,912 3 ** 18 = 387,420,489 (< pond_capacity, Day 19 not full yet) 3 ** 19 = 1,162,261,467 (>= pond_capacity, full after 19 transitions -> Day 20!) second_patch_full_day = 20 Task 3 (coin_count = 24, total_cents = 185): extra_cents = 185 - 5 * 24 = 65 dimes = 65 // 5 = 13, nickels = 24 - 13 = 11Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Timeline convention used across Tasks 1 and 2: # - Day 1 is the initial patch size (1 unit). # - Growth multiplies once between consecutive days, so after (d - 1) transitions # the patch size on Day d is rate ** (d - 1) units. def find_quarter_covered_day(cover_day: int, rate: int) -> int: """Return the earliest day (>= 1) on which the patch covers at least 1/4 of the pond.""" if rate == 1: # A rate-1 patch never changes size, so it already covered 100% (>= 1/4) on Day 1. return 1 day = cover_day # inverse_fraction tracks the denominator of coverage: on `day`, pond is (1 / inverse_fraction) full. inverse_fraction = 1 # Step backward while day > 1 and the previous day still has >= 1/4 coverage: # 1 / (inverse_fraction * rate) >= 1 / 4 is equivalent to inverse_fraction * rate <= 4. while day > 1 and inverse_fraction * rate <= 4: inverse_fraction *= rate day -= 1 return day def find_second_patch_full_day(cover_day: int, first_rate: int, second_rate: int) -> int: """Return the first day on which the second patch covers the whole pond, or -1 if never.""" # Measure capacity in exact Day-1 patch units: first patch grows (cover_day - 1) times to fill pond. pond_capacity = first_rate ** (cover_day - 1) if second_rate == 1: # Without growth, the second patch stays at 1 unit forever; it only fills a size-1 pond. return 1 if pond_capacity <= 1 else -1 current_size = 1 day = 1 # Multiply exact integers rather than taking float logarithms (math.log(125, 5) > 3.0 in IEEE-754). while current_size < pond_capacity: current_size *= second_rate day += 1 return day def solve_coins(coin_count: int, total_cents: int) -> Tuple[int, int]: """Return (nickels, dimes) for the given count and value in cents, or (-1, -1) if impossible.""" # Start with all nickels (5c each); swapping 1 nickel for 1 dime keeps count fixed and adds 5c. all_nickels_cents = 5 * coin_count extra_cents = total_cents - all_nickels_cents # extra_cents must be non-negative and a multiple of 5c to represent whole nickel-to-dime swaps. if extra_cents < 0 or extra_cents % 5 != 0: return -1, -1 dimes = extra_cents // 5 nickels = coin_count - dimes if nickels < 0: # Even making all coins dimes (10 * coin_count cents) cannot reach total_cents. return -1, -1 return nickels, dimes def solve_lily_pad_and_coins(cover_day: int, first_rate: int, second_rate: int, coin_count: int, total_cents: int) -> Dict[str, int]: if cover_day < 1 or first_rate < 1 or second_rate < 1: raise ValueError("cover_day and both growth rates must be at least 1") if coin_count < 0 or total_cents < 0: raise ValueError("coin_count and total_cents must be non-negative") nickels, dimes = solve_coins(coin_count, total_cents) return { "quarter_covered_day": find_quarter_covered_day(cover_day, first_rate), "second_patch_full_day": find_second_patch_full_day(cover_day, first_rate, second_rate), "nickels": nickels, "dimes": dimes, }✅ Submit now — all tests should pass.
Intuition & how it works
Each of the three mini-problems becomes straightforward as soon as we pick the right unit of measurement. Tasks 1 and 2 model exponential growth — a process where a quantity multiplies by a fixed factor each day rather than adding a constant slice. Rewinding the timeline backward from cover_day turns multiplication into division: for a doubling colony that reaches 100% on Day 30, stepping back one day cuts coverage to 1/2 (Day 29) and stepping back one more day cuts it to 1/4 (Day 28). For Task 2, measuring full capacity in units of "one Day-1 colony" means the basin holds first_rate ** (cover_day - 1) units, and we multiply the second colony's size upward from 1 using Python's arbitrary-precision integers (whole numbers that expand to any digit count without overflowing or rounding) until it reaches that capacity. Task 3 is a system of linear equations — two simultaneous linear equations over two unknown counts — which also has a clean physical picture: start with coin_count nickels (5 cents each), and observe that swapping one nickel for one dime keeps the coin count unchanged while adding +5 cents!
Why do tempting shortcuts fail? Dividing cover_day by 4 or 2 in Task 1 confuses compound doubling with constant daily addition. Using floating-point logarithms like 1 + math.ceil(math.log(pond, second_rate)) in Task 2 breaks on exact powers because of floating-point rounding error — tiny binary approximation errors in standard float numbers (for instance, math.log(125, 5) evaluates to 3.0000000000000004, tricking ceil into returning 4 instead of 3!). Similarly, computing Task 3 in floating-point dollars (0.05 and 0.10) invites decimal rounding bugs that vanish when working in integer cents.
Let's trace Example 2 (cover_day = 7, first_rate = 2, second_rate = 4, coin_count = 16, total_cents = 110):
Task 1 (backward from Day 7, rate = 2):
Day 7: 1/1 full -> Day 6: 1/2 full -> Day 5: 1/4 full => quarter_covered_day = 5
Task 2 (basin = 2^(7 - 1) = 64 Day-1 units, second_rate = 4):
Day 1: 1 -> Day 2: 4 -> Day 3: 16 -> Day 4: 64 >= 64
=> second_patch_full_day = 4
Task 3 (16 coins worth 110 cents):
16 nickels = 80c; extra = 110c - 80c = 30c; 30 // 5 = 6 swaps
=> dimes = 6, nickels = 16 - 6 = 10
Complexity
- Task 1 (
find_quarter_covered_day):- Time:
O(1). Iffirst_rate == 1, we return1immediately; for anyfirst_rate >= 2,inverse_fractionat least doubles each iteration and stops as soon asinverse_fraction * rate > 4(at most2loop steps!). - Space:
O(1). Only two integers (dayandinverse_fraction) are stored.
- Time:
- Task 2 (
find_second_patch_full_day):- Time:
O(cover_day^2)bit operations (for fixed small rates).pond_capacityhasB = O(cover_day * log(first_rate))bits, and thewhileloop runsO(B / log(second_rate))iterations, each multiplying an integer of up toBbits bysecond_rateinO(B)bit operations — finishing in microseconds for practicalcover_dayvalues. - Space:
O(cover_day)bits (for fixed rates), to store the two big integerspond_capacityandcurrent_size.
- Time:
- Task 3 (
solve_coins):- Time and Space:
O(1). It performs a fixed number of integer subtractions, modulo checks, and divisions.
- Time and Space:
Edge cases
- Basin fills within the first three days (
cover_dayis1,2, or3): Stepping backward stops atday == 1(while day > 1) because no Day0exists (for example,cover_day = 2, rate = 2starts1/2full on Day1, which is already>= 1/4, so it returns1). - Growth rates with no exact
1/4day: As in Example 3 (first_rate = 3), coverage steps... -> 1/9 -> 1/3 -> 1, so1/3(cover_day - 1) is the earliest day with at least1/4coverage; forfirst_rate >= 5,cover_day - 1has<= 1/5 < 1/4, socover_dayitself is returned. - Growth rate equal to
1: Iffirst_rate == 1, the basin holds1unit and was already full on Day1, so Tasks 1 and 2 both return1. Iffirst_rate >= 2, cover_day >= 2, andsecond_rate == 1, the second colony stays at size1forever and returns-1. - Equal rates (
first_rate == second_rate >= 2): Exact integer multiplication hitscurrent_size == pond_capacityoncover_daywithout any float-log off-by-one error. - Impossible coin totals: Totals below
5 * coin_count(extra_cents < 0), above10 * coin_count(nickels < 0, as in Example 3's8coins vs95cents), or not divisible by5(extra_cents % 5 != 0) all cleanly return(-1, -1). Zero coins worth zero cents (0, 0) validly returns(0, 0).
Common mistakes
- Proportional / linear thinking on Task 1: Answering
cover_day // 4(7for Day30) instead of rewinding two doublings to Day28. - Off-by-one exponent (
rate ** cover_dayinstead ofrate ** (cover_day - 1)): On Day1the colony has multiplied0times, so by Day30it has multiplied29times, not30. Using2 ** 30and3 ** nshiftssecond_patch_full_dayoff by a day. - Using
math.ceil(math.log(pond, second_rate)): Fails on exact powers likecover_day = 4, first_rate = 5, second_rate = 5becausemath.log(125, 5)is slightly above3.0in binary floating point. - Forgetting the
second_rate == 1infinite-loop guard: Multiplyingcurrent_sizeby1insidewhile current_size < pond_capacity:never progresses whenpond_capacity > 1. - Skipping non-negativity or divisibility checks on coins: Pure algebra gives negative nickels (
nickels = -3, dimes = 11) on Example 3 (coin_count = 8, total_cents = 95), violating the non-negative count rule.
Follow-up questions
- How does the quarter-coverage day change when the daily growth factor is 4 instead of 2? Each backward step divides coverage by
4rather than2, so the colony covered exact1/4capacity just one day prior tocover_day(cover_day - 1, such as Day29whencover_day = 30, providedcover_day >= 2). More generally, an exact quarter occurslog_r(4)days beforecover_day, which lands on an integer day for integerronly whenr = 2(2days earlier) orr = 4(1day earlier). - Suppose 25-cent quarters are also allowed; what extra constraint is needed to determine a unique count for each denomination? Two linear equations (
n + d + q = coin_countand5n + 10d + 25q = total_cents) leave one degree of freedom across three unknowns — for instance, with24coins totaling185cents, simplifying yieldsd + 4q = 13, admitting four valid non-negative triples(n, d, q):(11, 13, 0),(14, 9, 1),(17, 5, 2), and(20, 1, 3). Pinning down a single solution requires a third independent equation, such as the exact count of one denomination, a fixed ratio between two coin types, or the total mass of the pouch given distinct coin weights. - How can you compute a patch's exact size on Day N for an arbitrary growth factor r in logarithmic steps? Instead of multiplying by
rinside anO(N)loop, evaluateinitial_size * (r ** (N - 1))via exponentiation by squaring — an algorithm that repeatedly squares the base (r^2, r^4, r^8, ...) sor ** (N - 1)takes onlyO(log N)multiplications (which Python's built-inpow(r, N - 1)andpow(r, N - 1, mod)already implement). Whenris a floating-point factor andNis large enough to overflow 64-bit floats, work in log space by storingln(size) = ln(initial_size) + (N - 1) * ln(r), turning huge exponentiations into safe addition and multiplication.
Follow-up questions
- How does the quarter-coverage day change when the daily growth factor is 4 instead of 2?
- Suppose 25-cent quarters are also allowed; what extra constraint is needed to determine a unique count for each denomination?
- How can you compute a patch's exact size on Day N for an arbitrary growth factor r in logarithmic steps?
Similar questions
- Multi-Tap Phone Keypad String Encoder
- Propositional Implication Deduction Engine
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations