Cracking LeetCode’s 3116 with binary search and inclusion-exclusion

A brute-force loop over billions of multiples is the first thought when you see LeetCode 3116—until you realize k can reach 2×10⁹ and the clock is ticking. The twist isn’t the problem statement; it’s the elegant pairing of binary search on the answer with an inclusion-exclusion count that turns a 26% acceptance-rate monster into a tractable puzzle.
Binary search on the answer
Instead of generating every candidate up to k, the trick is to binary-search for the smallest X such that the number of valid amounts ≤ X is at least k. The search space is bounded by k times the maximum coin value, keeping the logarithm small. The real bottleneck isn’t the binary search itself—it’s counting how many multiples of any non-empty subset of coins are ≤ X without double-counting overlaps.
Inclusion-exclusion via bitmask
The count(X) routine leverages inclusion-exclusion over the coin set through bitmask iteration. For each non-empty subset, compute its least common multiple (LCM) using GCD, then decide whether to add or subtract its multiples based on the parity of the subset size. When LCM exceeds X, you can break early, pruning the search tree. The complexity becomes O(n · 2ⁿ · log(k·M)), clean enough to run within seconds even for the upper limits.
Why it matters
LeetCode 3116 isn’t just another counting problem; it’s a microcosm of how algorithmic thinking trumps brute force. By recognizing monotonicity and applying inclusion-exclusion with bitmask efficiency, coders sidestep an impossible enumeration. The lesson extends beyond contests: any scenario that demands counting valid combinations under constraints can benefit from the same divide-and-conquer mindset.
Source: DEV Community. AI-assisted editorial synthesis — TechnoExpress.

