Distribute Repeating Integers - Problem

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-th customer gets exactly quantity[i] integers
  • The integers the i-th customer gets are all equal
  • Every customer is satisfied

Return true if it is possible to distribute nums according to the above conditions.

Input & Output

Example 1 — Basic Distribution
$ Input: nums = [1,2,3,4], quantity = [2]
Output: false
💡 Note: No single value appears twice. Customer wants 2 identical items but max frequency is 1.
Example 2 — Successful Distribution
$ Input: nums = [1,2,3,3], quantity = [2]
Output: true
💡 Note: Value 3 appears twice. Customer gets [3,3] which satisfies quantity = 2.
Example 3 — Multiple Customers
$ Input: nums = [1,1,2,2], quantity = [2,2]
Output: true
💡 Note: Customer 0 gets [1,1], Customer 1 gets [2,2]. Both satisfied with identical items.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ 1000
  • m == quantity.length
  • 1 ≤ m ≤ 10
  • 1 ≤ quantity[i] ≤ 105
  • There are at most 50 unique values in nums.

Visualization

Tap to expand
Distribute Repeating Integers INPUT nums array: 1 2 3 4 [0] [1] [2] [3] quantity array: 2 [0] Value Frequency: 1 appears: 1 time 2 appears: 1 time 3 appears: 1 time 4 appears: 1 time ALGORITHM STEPS 1 Count Frequencies Map each unique value to its count in nums 2 Sort Quantities Sort descending for greedy assignment 3 Bitmask DP dp[mask] = can satisfy customers in mask? 4 Check Assignments Try assigning each freq to subset of customers DP State Check: Need: 2 same integers Have: all freq = 1 No value has count >= 2 FINAL RESULT Customer needs: 2 same integers Available values: 1 2 3 4 Each appears only once! Cannot satisfy requirement Output: false Distribution impossible Key Insight: Bitmask DP tracks which subset of customers can be satisfied. For each unique value's frequency, try all subsets of remaining customers whose total demand <= frequency. If no value can provide enough identical integers (like needing 2 when max count is 1), return false. TutorialsPoint - Distribute Repeating Integers | DP with Bitmask
Asked in
Amazon 45 Google 32 Microsoft 28 Facebook 21
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen