Minimum Threshold for 5-and-21 Integer Combinations

Medium · Coding & Algorithms · Data Scientist · Online Assessment

Problem Statement

Consider building integers by combining any non-negative number of 5s and 21s. Specifically, an integer x is called achievable if there exist integers a >= 0 and b >= 0 such that:

x = 5 * a + 21 * b

Using zero copies of either value is valid (for instance, 5 = 5 * 1 + 21 * 0 and 21 = 5 * 0 + 21 * 1 are both achievable).

Implement smallest_n_for_5_and_21_sums() to compute and return the minimum positive integer N with the guarantee that every integer x >= N (N, N + 1, N + 2, ... without exception) is achievable.

Examples

Example 1

Checking individual candidate totals with building blocks 5 and 21:

x = 57  ->  achievable, since 57 = 3 * 5 + 2 * 21 (15 + 42)
x = 29  ->  NOT achievable:
              b = 0 gives remainder 29 - 0  = 29 (not divisible by 5)
              b = 1 gives remainder 29 - 21 = 8  (not divisible by 5)
              b >= 2 exceeds 29 (2 * 21 = 42 > 29)

Explanation: Because 29 cannot be written as 5 * a + 21 * b for non-negative integers a and b, the cutoff N for (5, 21) must be strictly greater than 29.

Example 2

Illustrating the threshold definition on a smaller analogous pair (3, 7) instead of (5, 21):

Building blocks: (3, 7)
  x = 11  ->  NOT achievable (neither 11 nor 11 - 7 = 4 is divisible by 3)
  x = 12  ->  4 * 3 + 0 * 7
  x = 13  ->  2 * 3 + 1 * 7
  x = 14  ->  0 * 3 + 2 * 7

Explanation: Once three consecutive integers (12, 13, 14) are achievable using 3 and 7, every larger integer follows by repeatedly adding 3, making 12 the minimum threshold for (3, 7). Calling smallest_n_for_5_and_21_sums() returns the corresponding minimum threshold N for (5, 21).

Constraints

  • Multipliers a and b must be non-negative integers (a >= 0, b >= 0).
  • smallest_n_for_5_and_21_sums() takes zero arguments and returns a Python int.

Step-by-step walkthrough

  1. Restate the problem and check when an answer exists

    We call an integer x achievable if we can build it by adding some non-negative number of 5s and some non-negative number of 21s:

    x = 5 * a + 21 * b    where a >= 0 and b >= 0 are integers
    

    Using zero of one kind is allowed: 5 = 5 * 1 + 21 * 0 and 21 = 5 * 0 + 21 * 1 are both achievable, as is 57 = 5 * 3 + 21 * 2 from Example 1. We want smallest_n_for_5_and_21_sums() to return the minimum positive integer N such that every integer from N onward (N, N + 1, N + 2, ... forever) is achievable.

    Rather than returning a hardcoded magic constant with no explanation, we will write a clean general function smallest_always_representable(a, b) and call it with (5, 21).

    First, verify why a finite cutoff N exists at all: - 5 and 21 are coprime, meaning their greatest common divisor (gcd(5, 21), the largest integer dividing both evenly) is 1. - If two denominations shared a factor bigger than 1 — say 4 and 6 (gcd = 2) — then 4 * a + 6 * b would always be even, so odd numbers would fail forever and no finite N would exist.

  2. Brute force for one target, and why we need a stopping rule

    To test whether a single target x is achievable, we can try every valid count b of 21s (b = 0, 1, ..., x // 21) and check whether the leftover x - 21 * b is divisible by 5:

    Example 1 check (x = 29):
      b = 0 -> leftover 29  (not divisible by 5)
      b = 1 -> leftover 8   (not divisible by 5)
      => 29 is NOT achievable!
    
    Later gap check (x = 79):
      b = 0 -> leftover 79  (not divisible by 5)
      b = 1 -> leftover 58  (not divisible by 5)
      b = 2 -> leftover 37  (not divisible by 5)
      b = 3 -> leftover 16  (not divisible by 5)
      => 79 is NOT achievable either!
    

    We can scan x = 1, 2, 3, ... upward, spotting which numbers work and which fail. However, the problem asks about every integer >= N — an infinite set of numbers! How do we know with 100% certainty when the gaps have ended forever?

  3. Key idea: five consecutive achievable numbers unlock everything above

    Just like Example 2 showed 3 consecutive hits (12, 13, 14) unlocking everything above 12 for (3, 7), suppose we find 5 achievable integers in a row for (5, 21): m, m + 1, m + 2, m + 3, m + 4. What happens to the next 5 integers after them?

    Base streak of 5:   m       m+1     m+2     m+3     m+4     (all achievable)
    Add one 5 (+5):     m+5     m+6     m+7     m+8     m+9     (all achievable!)
    Add another 5 (+5): m+10    m+11    m+12    m+13    m+14    (all achievable!)
    ...                 ...     ...     ...     ...     ...     (forever!)
    

    Adding 5 to an achievable number simply increases its multiplier a by 1, so the result is guaranteed to be achievable too! Thus, the very first time our upward scan sees min(a, b) (here 5) achievable numbers in a row:

    1. Everything from the start of that streak (m) onward is achievable, because +5 tiles every larger integer without leaving gaps.
    2. No smaller starting value works, because m - 1 was not achievable (if m - 1 had been achievable, the streak of 5 would have completed one step earlier!).

    So m is provably the exact minimal N.

  4. Fast dynamic programming check as we scan upward

    Instead of re-checking every multiple of 21 from scratch at each x, we can use dynamic programming (solving each number in O(1) time by looking up smaller numbers we already solved).

    Think about the last piece added to form a positive total v: - Either the combination uses at least one 5, meaning v - 5 is also a valid combination of 5s and 21s; - Or the combination uses at least one 21, meaning v - 21 is also a valid combination of 5s and 21s.

    Seeding can_make[0] = True (since 0 = 5 * 0 + 21 * 0 uses zero pieces), each new integer v only needs two boolean lookups: can_make[v - 5] and can_make[v - 21].

  5. Verify by hand using remainders modulo 5

    Before coding, we can predict the exact answer on paper using remainders modulo 5 (the leftover after dividing by 5).

    Adding 5s never changes a number's remainder modulo 5. Meanwhile, 21 = 4 * 5 + 1 adds 1 to the remainder modulo 5. Here is the smallest achievable non-negative integer in each of the five remainder lanes 0, 1, 2, 3, 4:

    Remainder mod 5 | Minimum copies of 21 needed | Smallest achievable value | Values in this lane
    ----------------+-----------------------------+---------------------------+-------------------------
           0        | 0 copies  (0 * 21)          |  0                        |  0,  5, 10, 15, ...
           1        | 1 copy    (1 * 21)          | 21                        | 21, 26, 31, 36, ...
           2        | 2 copies  (2 * 21)          | 42                        | 42, 47, 52, 57, ...
           3        | 3 copies  (3 * 21)          | 63                        | 63, 68, 73, 78, ...
           4        | 4 copies  (4 * 21)          | 84                        | 84, 89, 94, 104, ...
    

    Look at the slowest lane — remainder 4: - Its very first achievable value is 84 (notice how 29 from Example 1 sits in lane 4 well below 84, which is why 29 failed!). - One step below 84 in lane 4 is 84 - 5 = 79, which is unreachable! - Every integer >= 80 sits at or above its lane's starting value (80 in lane 0, 81 in lane 1, 82 in lane 2, 83 in lane 3, 84 in lane 4).

    Therefore, 79 is the largest unreachable integer, and N = 80. (In general, for any coprime integers a, b >= 2, the largest unreachable integer is a * b - a - b, giving N = a * b - a - b + 1 = 5 * 21 - 5 - 21 + 1 = 80 — matching 3 * 7 - 3 - 7 + 1 = 12 from Example 2!)

  6. Code the scan and trace around N = 80

    Let's translate the upward scan into clean Python and watch how consecutive_run behaves right around 80:

    current_value:    74  75  76  77  78  79  80  81  82  83  84
    is_reachable:      F   T   T   T   T   F   T   T   T   T   T
    consecutive_run:   0   1   2   3   4   0   1   2   3   4   5  <-- hits 5!
    
    Return: current_value - smaller_coin + 1 = 84 - 5 + 1 = 80
    

    Notice how 75, 76, 77, 78 reach a streak of 4 — just one short — before 79 resets consecutive_run to 0. Then 80, 81, 82, 83, 84 hit a full streak of 5, stopping the loop at current_value = 84 and returning 80.

    from math import gcd
    
    
    def smallest_always_representable(a: int, b: int) -> int:
        # Guard: if a and b share a common factor > 1 (e.g., 4 and 6), every sum
        # is a multiple of gcd(a, b), so non-multiples are unreachable forever.
        if a < 1 or b < 1 or gcd(a, b) != 1:
            raise ValueError("a and b must be positive and coprime")
    
        # smaller_coin: once this many consecutive integers are representable,
        # every larger integer can be formed by adding copies of smaller_coin.
        smaller_coin = min(a, b)
    
        # can_make: boolean list where can_make[v] is True iff v = a*x + b*y
        # for non-negative integers x, y; seeded with 0 = a*0 + b*0.
        can_make = [True]
    
        # consecutive_run: how many integers in a row ending at current_value are True.
        consecutive_run = 0
        current_value = 0
    
        # Scan upward one integer at a time until we hit a full run of length smaller_coin.
        while consecutive_run < smaller_coin:
            current_value += 1
    
            # A positive value v is representable iff removing one 'a' or one 'b'
            # lands on an already-representable non-negative value.
            reachable_via_a = current_value >= a and can_make[current_value - a]
            reachable_via_b = current_value >= b and can_make[current_value - b]
            is_reachable = reachable_via_a or reachable_via_b
            can_make.append(is_reachable)
    
            if is_reachable:
                consecutive_run += 1
            else:
                # A gap breaks the streak; any valid N must start strictly after this value.
                consecutive_run = 0
    
        # current_value is the LAST element of a run of length smaller_coin,
        # so subtracting (smaller_coin - 1) gives the FIRST element of that run.
        return current_value - smaller_coin + 1
    
  7. Complete solution

    Wrapping the helper inside the judged function smallest_n_for_5_and_21_sums():

    from typing import Any, Dict, List, Optional, Set, Tuple
    from math import gcd
    
    
    def smallest_n_for_5_and_21_sums() -> int:
        # Solve the specific (5, 21) problem via the general two-coin scan helper.
        return smallest_always_representable(5, 21)
    
    
    def smallest_always_representable(a: int, b: int) -> int:
        # Guard: if a and b share a common factor > 1 (e.g., 4 and 6), every sum
        # is a multiple of gcd(a, b), so non-multiples are unreachable forever.
        if a < 1 or b < 1 or gcd(a, b) != 1:
            raise ValueError("a and b must be positive and coprime")
    
        # smaller_coin: once this many consecutive integers are representable,
        # every larger integer can be formed by adding copies of smaller_coin.
        smaller_coin = min(a, b)
    
        # can_make: boolean list where can_make[v] is True iff v = a*x + b*y
        # for non-negative integers x, y; seeded with 0 = a*0 + b*0.
        can_make = [True]
    
        # consecutive_run: how many integers in a row ending at current_value are True.
        consecutive_run = 0
        current_value = 0
    
        # Scan upward one integer at a time until we hit a full run of length smaller_coin.
        while consecutive_run < smaller_coin:
            current_value += 1
    
            # A positive value v is representable iff removing one 'a' or one 'b'
            # lands on an already-representable non-negative value.
            reachable_via_a = current_value >= a and can_make[current_value - a]
            reachable_via_b = current_value >= b and can_make[current_value - b]
            is_reachable = reachable_via_a or reachable_via_b
            can_make.append(is_reachable)
    
            if is_reachable:
                consecutive_run += 1
            else:
                # A gap breaks the streak; any valid N must start strictly after this value.
                consecutive_run = 0
    
        # current_value is the LAST element of a run of length smaller_coin,
        # so subtracting (smaller_coin - 1) gives the FIRST element of that run.
        return current_value - smaller_coin + 1
    

    The minimum integer N from which every integer is achievable is 80.

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine weighing parcels on a balance using only 5-gram and 21-gram weights. Some totals like 57 = 3 * 5 + 2 * 21 work cleanly, while others like 29 or 79 cannot be formed at all, leaving gaps along the number line. However, the exact moment you can form 5 consecutive integers in a row (m, m + 1, m + 2, m + 3, m + 4), gaps disappear forever — because you can form the next 5 integers (m + 5 through m + 9) simply by adding one 5-gram weight to each of those 5 totals, and keep stepping forward by +5 endlessly! (Just as in Example 2, where hitting 3 consecutive achievable values 12, 13, 14 with (3, 7) unlocked every integer >= 12.)

A naive approach checks numbers up to an arbitrary ceiling like 1,000 by trying every count of 21s for each candidate. That approach has two flaws: without the "5-in-a-row" stopping rule, you have no mathematical guarantee that another gap isn't hiding beyond 1,000, and testing every multiple of 21 from scratch repeats work we already completed. Instead, we use dynamic programming (storing boolean answers for smaller integers in a list so each new integer is solved in constant time): a positive integer v is achievable if and only if v - 5 or v - 21 was already achievable.

Watch how the upward scan finishes right around the threshold: 1. At 75, 76, 77, 78, we hit four achievable integers in a row (15 * 5, 21 + 11 * 5, 2 * 21 + 7 * 5, 3 * 21 + 3 * 5), then 79 fails because subtracting 0, 1, 2, or 3 copies of 21 leaves 79, 58, 37, 16 — none divisible by 5 — resetting the streak to 0. 2. Next come 80 = 16 * 5, 81 = 21 + 12 * 5, 82 = 2 * 21 + 8 * 5, 83 = 3 * 21 + 4 * 5, and 84 = 4 * 21: 5 achievable integers in a row! 3. The loop stops at 84 and returns the start of that 5-integer streak, 84 - 5 + 1 = 80.

Complexity

  • Time: O(a * b) for the general helper smallest_always_representable(a, b) (which is O(1) for the fixed pair (5, 21), executing only 84 loop iterations). Each integer up to a * b - max(a, b) is visited once and checked with two O(1) list lookups. (Using the two-denomination closed form a * b - a - b + 1 directly takes O(1) arithmetic for any coprime a, b >= 2, while the DP scan derives the answer from first principles without memorizing a formula.)
  • Space: O(a * b) for the can_make boolean list (85 booleans for 5 and 21). Because each step only looks back at v - a and v - b, a sliding ring buffer of size max(a, b) could shrink auxiliary memory to O(max(a, b)) for very large inputs.

Edge cases

  • Zero copies of one building block (a = 0 or b = 0): Totals like 5 = 1 * 5 + 0 * 21 and 21 = 0 * 5 + 1 * 21 are valid; seeding can_make[0] = True ensures can_make[5] and can_make[21] both evaluate to True.
  • Zero itself (0): 0 = 0 * 5 + 0 * 21 seeds the dynamic programming table, while the upward scan starts testing positive integers at current_value = 1.
  • Non-coprime inputs (e.g., 4 and 6): Two integers are coprime when their greatest common divisor (gcd, the largest integer dividing both evenly) is 1. When gcd(a, b) > 1, only multiples of that divisor can ever be formed, so smallest_always_representable raises ValueError instead of looping forever.
  • Unit denomination (1 and 21): Every positive integer is immediately achievable using copies of 1; at current_value = 1 the streak hits min(1, 21) = 1 and the helper returns 1.

Common mistakes

  • Returning 79 instead of 80: 79 is the Frobenius number (the largest integer that cannot be formed from non-negative multiples of the denominations). The problem asks for the minimum N where every integer >= N is achievable, which is 79 + 1 = 80.
  • Off-by-one when computing the start of the streak: When consecutive_run reaches 5 at current_value = 84, the five numbers are 80, 81, 82, 83, 84, so the first element is 84 - 5 + 1 = 80, not 84 - 5 = 79.
  • Stopping after fewer than min(a, b) consecutive hits: Seeing 4 achievable numbers in a row (75, 76, 77, 78) is not enough — adding 5 jumps from 75..78 to 80..83, skipping right over 79!
  • Applying a * b - a - b + 1 without checking gcd(a, b) == 1 and a, b >= 2: Plugging (4, 6) into the formula outputs 15 even though 15 is odd and impossible, and plugging (1, 5) outputs 0 instead of the smallest positive integer 1.

Alternative approaches

  • Closed-form Chicken McNugget theorem: For coprime integers a, b >= 2, return a * b - a - b + 1 directly (5 * 21 - 5 - 21 + 1 = 80) in O(1) time and O(1) space. Pairing this formula with the modular-remainder proof or the DP scan demonstrates both number-theory fluency and coding rigor.
  • Remainder-lane computation (O(min(a, b))): Track the smallest achievable value for each remainder modulo min(a, b) by stepping through 0, b, 2 * b, ..., (a - 1) * b; the largest of those starting values minus a, plus 1, gives N in just 5 steps.

Follow-up questions

  • What closed-form expression gives the threshold N for any two coprime positive integers a and b (both at least 2), and why does it work? When a, b >= 2 satisfy gcd(a, b) = 1, the largest unreachable integer is a * b - a - b, so the threshold is N = a * b - a - b + 1. Partitioning integers by their remainder modulo a (the leftover after dividing by a), the multiples 0, b, 2 * b, ..., (a - 1) * b visit all a distinct remainder lanes because a and b share no common factor, and r * b is the minimum achievable total in its lane. The last lane to activate starts at (a - 1) * b, making (a - 1) * b - a = a * b - a - b the final unreachable integer.
  • How many positive integers in total fail to have a valid non-negative representation 5a + 21b? For any coprime a, b >= 1, exactly (a - 1) * (b - 1) / 2 positive integers are unreachable — for 5 and 21, that is 4 * 20 / 2 = 40 unreachable integers out of 1..79 (leaving 39 achievable ones below 80). In each remainder lane seeded at r * b (1 <= r <= a - 1), the positive integers strictly below r * b sharing that remainder are r * b - a, r * b - 2 * a, ..., giving r * b // a missing values per lane whose sum across r = 1 .. a - 1 simplifies to (a - 1) * (b - 1) / 2.
  • How would you compute the threshold N algorithmically when three or more positive denominations are available? No simple closed-form formula exists for three or more denominations, so we generalize the remainder-lane method using Dijkstra's shortest-path algorithm (a graph search that repeatedly settles the minimum-cost reachable state first). Let m be the smallest denomination (say 6 for [6, 9, 20]): create m remainder states 0 .. m - 1, initialize dist[0] = 0, and from remainder r transition along each denomination c to (r + c) % m with candidate total dist[r] + c. Provided the gcd of all denominations is 1, every remainder becomes reachable, and max(dist) - m + 1 gives N (49 - 6 + 1 = 44 for [6, 9, 20]).

Follow-up questions

Similar questions

More Schonfeld interview questions

All 2 Schonfeld questions →