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

  1. Quarter-capacity milestone ("quarter_covered_day"):
    • A water-plant colony starts on Day 1 with an area of 1 unit.
    • Between each Day d and Day d + 1, its area multiplies by the integer factor first_rate, so on Day d (d >= 1) its area is first_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 least 1/4 of full basin capacity.
  2. Alternative growth schedule ("second_patch_full_day"):
    • A separate colony also starts on Day 1 at 1 unit of area, multiplying by second_rate between consecutive days (second_rate ** (d - 1) units on Day d).
    • Return the earliest integer day (>= 1) on which this second colony alone covers at least 100% of full basin capacity, or -1 if it never reaches full capacity.
  3. Two-coin breakdown ("nickels" and "dimes"):
    • A pouch holds coin_count coins consisting solely of 5-cent nickels and 10-cent dimes whose combined worth equals total_cents cents.
    • Return the non-negative integer counts for "nickels" and "dimes". If no non-negative integer pair satisfies both coin_count and total_cents, set both "nickels" and "dimes" to -1.
  4. Input validation:
    • Raise ValueError if cover_day < 1, first_rate < 1, second_rate < 1, coin_count < 0, or total_cents < 0.

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 Day 30, so coverage was 1/2 on Day 29 and 1/4 on Day 28.
  • Second colony: Full capacity is 2^29 = 536,870,912 Day-1 units. Tripling from 1 gives 3^18 = 387,420,489 on Day 19 (short) and 3^19 = 1,162,261,467 on Day 20 (full).
  • Coins: 11 nickels (55 cents) plus 13 dimes (130 cents) use 24 coins and sum to 185 cents.

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 Day 5.
  • Second colony: Full capacity is 2^6 = 64 units; quadrupling reaches 4^3 = 64 after 3 daily transitions, which is Day 4.
  • Coins: 10 nickels (50 cents) and 6 dimes (60 cents) total 16 coins worth 110 cents.

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 is 1/3 >= 1/4 on Day 14 and 1/9 < 1/4 on Day 13, so Day 14 is the earliest day at or above 1/4.
  • Second colony: A factor-1 colony stays at 1 unit forever and never reaches 3^14 units (-1).
  • Coins: Eight coins can be worth at most 8 * 10 = 80 cents, so 95 cents is unreachable (-1, -1).

Constraints

  • cover_day >= 1, first_rate >= 1, second_rate >= 1 (raise ValueError otherwise)
  • coin_count >= 0, total_cents >= 0 (raise ValueError otherwise)
  • Typical valid inputs satisfy 1 <= cover_day <= 10^4, 1 <= first_rate, second_rate <= 10, 0 <= coin_count <= 10^6, and 0 <= 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

  1. Understand the three tasks and the day-numbering model

    A single call to solve_lily_pad_and_coins answers 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 (1 unit).
    • Growth happens once between consecutive days: moving from Day d to Day d + 1 multiplies the patch size by its rate.
    • Therefore, on Day d, a patch has multiplied d - 1 times (not d times!), so its size is rate ** (d - 1) units, and day numbers never go below 1.

    When first_rate is 2 or 4, the pond hits exact 1/4 coverage on an integer day (2 days back or 1 day back). For a general integer rate like 3 (where coverage goes 1/9 -> 1/3 -> 1), no day is exact 1/4, so we report the first day with at least 1/4 coverage (which equals the exact quarter-day whenever one exists). Similarly, Task 2 returns -1 if the second patch never fills the pond, and Task 3 returns -1 for both coins if no non-negative integer split exists.

  2. 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 of 30 is around Day 7 or 8." That confuses multiplying by 2 with 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 denominator inverse_fraction so that on day, the pond is 1 / inverse_fraction covered:

    • On cover_day, inverse_fraction = 1 (1/1 full).
    • Stepping back one day would make the coverage 1 / (inverse_fraction * rate).
    • That earlier day is still at least 1/4 covered if and only if 1 / (inverse_fraction * rate) >= 1 / 4, which cross-multiplies cleanly in integers to inverse_fraction * rate <= 4.
    • Also stop if day == 1 (the patch did not exist on Day 0), and handle rate == 1 immediately (a non-growing patch that is full on cover_day was already 100% full on Day 1).
    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
    
  3. 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 size 1 unit!

    • Between Day 1 and cover_day, the first patch multiplies cover_day - 1 times, so the pond's total capacity is pond_capacity = first_rate ** (cover_day - 1) units.
    • On Day n, the second patch has multiplied n - 1 times, so its size is second_rate ** (n - 1) units.
    • We want the smallest day n >= 1 such that second_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 to 3.0000000000000004, so math.ceil(...) rounds it up to 4 instead of 3 — reporting Day 5 when 5^3 = 125 was already full on Day 4!

    Python's integers have unlimited precision, so we can start current_size = 1 on day = 1 and multiply by second_rate until current_size >= pond_capacity with zero rounding error. Just guard second_rate == 1 first so a non-growing second patch returns -1 (unless pond_capacity == 1, where Day 1 is 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
    
  4. Task 3: Solve the coin equations using the nickel-to-dime swap trick

    Work in integer cents (5 cents per nickel, 10 cents per dime) rather than floating-point dollars (0.05 and 0.10) so decimal rounding never touches our math. With nickels and dimes as our two unknowns:

    Equation 1 (coin count):   nickels + dimes       = coin_count
    Equation 2 (total value):  5 * nickels + 10 * dimes = total_cents
    

    Substitute nickels = coin_count - dimes from 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) / 5
    

    There is also a great mental picture for that exact formula: imagine laying coin_count nickels on the table first (5 * coin_count cents). Every time you swap 1 nickel for 1 dime, the total number of coins stays coin_count, and the total value goes up by +5 cents!

    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 = 185c
    

    For the solution to be valid non-negative integers, three checks must pass: 1. extra_cents >= 0 (otherwise even all nickels exceed total_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 of total_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, dimes
    
  5. Walk 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 = 11
    
  6. Complete 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). If first_rate == 1, we return 1 immediately; for any first_rate >= 2, inverse_fraction at least doubles each iteration and stops as soon as inverse_fraction * rate > 4 (at most 2 loop steps!).
    • Space: O(1). Only two integers (day and inverse_fraction) are stored.
  • Task 2 (find_second_patch_full_day):
    • Time: O(cover_day^2) bit operations (for fixed small rates). pond_capacity has B = O(cover_day * log(first_rate)) bits, and the while loop runs O(B / log(second_rate)) iterations, each multiplying an integer of up to B bits by second_rate in O(B) bit operations — finishing in microseconds for practical cover_day values.
    • Space: O(cover_day) bits (for fixed rates), to store the two big integers pond_capacity and current_size.
  • Task 3 (solve_coins):
    • Time and Space: O(1). It performs a fixed number of integer subtractions, modulo checks, and divisions.

Edge cases

  • Basin fills within the first three days (cover_day is 1, 2, or 3): Stepping backward stops at day == 1 (while day > 1) because no Day 0 exists (for example, cover_day = 2, rate = 2 starts 1/2 full on Day 1, which is already >= 1/4, so it returns 1).
  • Growth rates with no exact 1/4 day: As in Example 3 (first_rate = 3), coverage steps ... -> 1/9 -> 1/3 -> 1, so 1/3 (cover_day - 1) is the earliest day with at least 1/4 coverage; for first_rate >= 5, cover_day - 1 has <= 1/5 < 1/4, so cover_day itself is returned.
  • Growth rate equal to 1: If first_rate == 1, the basin holds 1 unit and was already full on Day 1, so Tasks 1 and 2 both return 1. If first_rate >= 2, cover_day >= 2, and second_rate == 1, the second colony stays at size 1 forever and returns -1.
  • Equal rates (first_rate == second_rate >= 2): Exact integer multiplication hits current_size == pond_capacity on cover_day without any float-log off-by-one error.
  • Impossible coin totals: Totals below 5 * coin_count (extra_cents < 0), above 10 * coin_count (nickels < 0, as in Example 3's 8 coins vs 95 cents), or not divisible by 5 (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 (7 for Day 30) instead of rewinding two doublings to Day 28.
  • Off-by-one exponent (rate ** cover_day instead of rate ** (cover_day - 1)): On Day 1 the colony has multiplied 0 times, so by Day 30 it has multiplied 29 times, not 30. Using 2 ** 30 and 3 ** n shifts second_patch_full_day off by a day.
  • Using math.ceil(math.log(pond, second_rate)): Fails on exact powers like cover_day = 4, first_rate = 5, second_rate = 5 because math.log(125, 5) is slightly above 3.0 in binary floating point.
  • Forgetting the second_rate == 1 infinite-loop guard: Multiplying current_size by 1 inside while current_size < pond_capacity: never progresses when pond_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 4 rather than 2, so the colony covered exact 1/4 capacity just one day prior to cover_day (cover_day - 1, such as Day 29 when cover_day = 30, provided cover_day >= 2). More generally, an exact quarter occurs log_r(4) days before cover_day, which lands on an integer day for integer r only when r = 2 (2 days earlier) or r = 4 (1 day 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_count and 5n + 10d + 25q = total_cents) leave one degree of freedom across three unknowns — for instance, with 24 coins totaling 185 cents, simplifying yields d + 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 r inside an O(N) loop, evaluate initial_size * (r ** (N - 1)) via exponentiation by squaring — an algorithm that repeatedly squares the base (r^2, r^4, r^8, ...) so r ** (N - 1) takes only O(log N) multiplications (which Python's built-in pow(r, N - 1) and pow(r, N - 1, mod) already implement). When r is a floating-point factor and N is large enough to overflow 64-bit floats, work in log space by storing ln(size) = ln(initial_size) + (N - 1) * ln(r), turning huge exponentiations into safe addition and multiplication.

Follow-up questions

Similar questions

More Epic Systems interview questions

All 3 Epic Systems questions →