Problem Description
You are given two integers k and x. For any number num, its price is defined as the count of set bits in its binary representation at positions x, 2x, 3x, … (with the least significant bit considered as position 1). The accumulated price of num is the sum of prices of all numbers from 1 to num. A number num is considered cheap if its accumulated price is less than or equal to k. The task is to return the greatest cheap number.
Key Insights
- The price of a single number is determined only by the bits in positions that are multiples of x.
- The accumulated price function from 1 to num is monotonic (non-decreasing); hence binary search can be applied to find the maximum num such that its accumulated price ≤ k.
- The contribution of each eligible bit position can be computed using a formula similar to counting set bits over a range. For a given bit position p (where p is a multiple of x), the count of ones among numbers from 1 to n is: • count = (n // (2^p)) * (2^(p-1)) + max(0, (n % (2^p)) − 2^(p-1) + 1)
- Sum the contributions for positions p = x, 2x, 3x, … (as long as 2^(p-1) ≤ n) to get the accumulated price function.
Space and Time Complexity
Time Complexity: O(log(high) * (max_bits)), where max_bits is the number of bit positions to check (roughly O(log n) at worst).
Space Complexity: O(1)
Solution
The solution uses binary search over the candidate numbers. A helper function f(n) computes the accumulated price for numbers from 1 to n by iterating over every eligible bit position (multiples of x) and using the counting formula described above. Since the accumulated price is monotonic, we can use binary search to find the largest number num for which f(num) ≤ k.
Data structures used: basic integer arithmetic and loop iteration.
Algorithmic approaches: binary search and bit manipulation.
Key tricks include breaking down the accumulated price by bit positions and computing the count in each complete block plus the remaining (partial block) portion.