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?- A. 24 21 10
- B. 20 21 10
- C. 20 20 10
- 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
- Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole…
- Problem: Camera clips (start, end) cover parts of an event lasting T = 10 minutes; clips may be trimmed. Find the minimum number of clips…
- Problem: A broken calculator shows start and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach target…
- Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right. python def mono(n): d = list(str(n)); mark =…
- Problem: A string has '(', ')' and '', where '' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible…
- Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag…