Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion: count(x) = x//a + x//b − x//lcm(a, b).

Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion: count(x) = x//a + x//b − x//lcm(a, b).
from math import gcd
def nth_magic(n, a, b):
    l = a * b // gcd(a, b); lo, hi = 1, n * min(a, b)
    while lo < hi:
        mid = (lo + hi) // 2
        if mid // a + mid // b - mid // l >= n: hi = mid
        else: lo = mid + 1
    return lo
print(nth_magic(7, 4, 6), nth_magic(10, 3, 5), nth_magic(5, 2, 4))
What is printed?
  1. A. 24 21 10
  2. B. 20 21 10
  3. C. 20 20 10
  4. D. 20 21 20

Correct answer: B. 20 21 10

Multiples of 4 or 6: 4, 6, 8, 12, 16, 18, 20 → 7th = 20 (12 is counted once thanks to − x//12; using a·b = 24 instead of the lcm would over-subtract). For 3 or 5: 3, 5, 6, 9, 10, 12, 15, 18, 20, 21 → 21. For 2 or 4 every multiple of 4 is already even → 10. The smallest x with count(x) ≥ n is always magical. O(log(n·min(a, b))), fine for n = 10⁹.

More Coding Interview Problems questions

Exams that ask this topic