Distribute Repeating Integers Problem
Description
LeetCode Problem 1655.
You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the i^th customer ordered. Determine if it is possible to distribute nums such that:
- The
i^thcustomer gets exactlyquantity[i]integers, - The integers the
i^thcustomer gets are all equal, and - Every customer is satisfied.
Return true if it is possible to distribute nums according to the above conditions.
Example 1:
Input: nums = [1,2,3,4], quantity = [2]
Output: false
Explanation: The 0^th customer cannot be given two different integers.
Example 2:
Input: nums = [1,2,3,3], quantity = [2]
Output: true
Explanation: The 0^th customer is given [3,3]. The integers [1,2] are not used.
Example 3:
Input: nums = [1,1,2,2], quantity = [2,2]
Output: true
Explanation: The 0^th customer is given [1,1], and the 1st customer is given [2,2].
Constraints:
n == nums.length1 <= n <= 10^51 <= nums[i] <= 1000m == quantity.length1 <= m <= 101 <= quantity[i] <= 10^5- There are at most
50unique values innums.
Solution
Approach: Bitmask DP + Subset Enumeration
Only how many times each value appears matters, so count the values and put the counts into an array arr of length n (at most 50).
There are at most 10 customers, so a set of customers fits in a bitmask. Precompute s[mask], the total quantity the customers in mask want.
Let f[i][j] be whether the first i + 1 counts in arr can serve exactly the customers in j. f[i][0] is always true. For j > 0:
- if
f[i-1][j]is true, valueisimply goes unused; - otherwise try every non-empty subset
kofjto be served by valuei: it works ifs[k] <= arr[i]and the restj ^ kwas possible with the earlier values (fori = 0, the rest must be empty, sok = j).
The answer is f[n-1][2^m - 1].
Complexity: O(n * 3^m) time and O(n * 2^m) space, where m is the number of customers.
class Solution:
def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:
m = len(quantity)
s = [0] * (1 << m)
for i in range(1, 1 << m):
for j in range(m):
if i >> j & 1:
s[i] = s[i ^ (1 << j)] + quantity[j]
break
cnt = Counter(nums)
arr = list(cnt.values())
n = len(arr)
f = [[False] * (1 << m) for _ in range(n)]
for i in range(n):
f[i][0] = True
for i, x in enumerate(arr):
for j in range(1, 1 << m):
if i and f[i - 1][j]:
f[i][j] = True
continue
k = j
while k:
ok1 = j == k if i == 0 else f[i - 1][j ^ k]
ok2 = s[k] <= x
if ok1 and ok2:
f[i][j] = True
break
k = (k - 1) & j
return f[-1][-1]