Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 ith customer ordered. Determine if it is possible to distribute nums such that:
ith customer gets exactly quantity[i] integers,ith customer gets are all equal, andReturn 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 0th customer cannot be given two different integers.
Example 2:
Input: nums = [1,2,3,3], quantity = [2] Output: true Explanation: The 0th 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 0th customer is given [1,1], and the 1st customer is given [2,2].
Constraints:
n == nums.length1 <= n <= 1051 <= nums[i] <= 1000m == quantity.length1 <= m <= 101 <= quantity[i] <= 10550 unique values in nums.Problem summary: 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 ith customer ordered. Determine if it is possible to distribute nums such that: The ith customer gets exactly quantity[i] integers, The integers the ith customer gets are all equal, and Every customer is satisfied. Return true if it is possible to distribute nums according to the above conditions.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Backtracking · Bit Manipulation
[1,2,3,4] [2]
[1,2,3,3] [2]
[1,1,2,2] [2,2]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1655: Distribute Repeating Integers
class Solution {
public boolean canDistribute(int[] nums, int[] quantity) {
int m = quantity.length;
int[] s = new int[1 << m];
for (int i = 1; i < 1 << m; ++i) {
for (int j = 0; j < m; ++j) {
if ((i >> j & 1) != 0) {
s[i] = s[i ^ (1 << j)] + quantity[j];
break;
}
}
}
Map<Integer, Integer> cnt = new HashMap<>(50);
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int n = cnt.size();
int[] arr = new int[n];
int i = 0;
for (int x : cnt.values()) {
arr[i++] = x;
}
boolean[][] f = new boolean[n][1 << m];
for (i = 0; i < n; ++i) {
f[i][0] = true;
}
for (i = 0; i < n; ++i) {
for (int j = 1; j < 1 << m; ++j) {
if (i > 0 && f[i - 1][j]) {
f[i][j] = true;
continue;
}
for (int k = j; k > 0; k = (k - 1) & j) {
boolean ok1 = i == 0 ? j == k : f[i - 1][j ^ k];
boolean ok2 = s[k] <= arr[i];
if (ok1 && ok2) {
f[i][j] = true;
break;
}
}
}
}
return f[n - 1][(1 << m) - 1];
}
}
// Accepted solution for LeetCode #1655: Distribute Repeating Integers
func canDistribute(nums []int, quantity []int) bool {
m := len(quantity)
s := make([]int, 1<<m)
for i := 1; i < 1<<m; i++ {
for j := 0; j < m; j++ {
if i>>j&1 == 1 {
s[i] = s[i^(1<<j)] + quantity[j]
break
}
}
}
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
n := len(cnt)
arr := make([]int, 0, n)
for _, x := range cnt {
arr = append(arr, x)
}
f := make([][]bool, n)
for i := range f {
f[i] = make([]bool, 1<<m)
f[i][0] = true
}
for i := 0; i < n; i++ {
for j := 0; j < 1<<m; j++ {
if i > 0 && f[i-1][j] {
f[i][j] = true
continue
}
for k := j; k > 0; k = (k - 1) & j {
ok1 := (i == 0 && j == k) || (i > 0 && f[i-1][j-k])
ok2 := s[k] <= arr[i]
if ok1 && ok2 {
f[i][j] = true
break
}
}
}
}
return f[n-1][(1<<m)-1]
}
# Accepted solution for LeetCode #1655: Distribute Repeating Integers
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]
// Accepted solution for LeetCode #1655: Distribute Repeating Integers
/**
* [1655] Distribute Repeating Integers
*
* 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, 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.length
* 1 <= n <= 10^5
* 1 <= nums[i] <= 1000
* m == quantity.length
* 1 <= m <= 10
* 1 <= quantity[i] <= 10^5
* There are at most 50 unique values in nums.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/distribute-repeating-integers/
// discuss: https://leetcode.com/problems/distribute-repeating-integers/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/distribute-repeating-integers/solutions/3187911/just-a-runnable-solution/
pub fn can_distribute(nums: Vec<i32>, quantity: Vec<i32>) -> bool {
let mut counts = std::collections::HashMap::new();
for n in nums.iter() {
*counts.entry(*n).or_insert(0) += 1;
}
let mut counts = counts.values().copied().collect::<Vec<_>>();
counts.sort_by(|a, b| b.cmp(a));
let mut quantity = quantity;
quantity.sort_by(|a, b| b.cmp(a));
Self::dfs_helper(&mut counts, &quantity, 0)
}
fn dfs_helper(counts: &mut Vec<i32>, quantity: &Vec<i32>, index: usize) -> bool {
if index == quantity.len() {
return true;
}
for i in 0..counts.len() {
if counts[i] >= quantity[index] {
let p = quantity[index];
counts[i] -= p;
if Self::dfs_helper(counts, quantity, index + 1) {
return true;
}
counts[i] += p;
}
}
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1655_example_1() {
let nums = vec![1, 2, 3, 4];
let quantity = vec![2];
let result = false;
assert_eq!(Solution::can_distribute(nums, quantity), result);
}
#[test]
fn test_1655_example_2() {
let nums = vec![1, 2, 3, 3];
let quantity = vec![2];
let result = true;
assert_eq!(Solution::can_distribute(nums, quantity), result);
}
#[test]
fn test_1655_example_3() {
let nums = vec![1, 1, 2, 2];
let quantity = vec![2, 2];
let result = true;
assert_eq!(Solution::can_distribute(nums, quantity), result);
}
}
// Accepted solution for LeetCode #1655: Distribute Repeating Integers
function canDistribute(nums: number[], quantity: number[]): boolean {
const m = quantity.length;
const s: number[] = new Array(1 << m).fill(0);
for (let i = 1; i < 1 << m; ++i) {
for (let j = 0; j < m; ++j) {
if ((i >> j) & 1) {
s[i] = s[i ^ (1 << j)] + quantity[j];
break;
}
}
}
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
const n = cnt.size;
const arr: number[] = [];
for (const [_, v] of cnt) {
arr.push(v);
}
const f: boolean[][] = new Array(n).fill(false).map(() => new Array(1 << m).fill(false));
for (let i = 0; i < n; ++i) {
f[i][0] = true;
}
for (let i = 0; i < n; ++i) {
for (let j = 0; j < 1 << m; ++j) {
if (i > 0 && f[i - 1][j]) {
f[i][j] = true;
continue;
}
for (let k = j; k > 0; k = (k - 1) & j) {
const ok1: boolean = (i == 0 && j == k) || (i > 0 && f[i - 1][j ^ k]);
const ok2: boolean = s[k] <= arr[i];
if (ok1 && ok2) {
f[i][j] = true;
break;
}
}
}
}
return f[n - 1][(1 << m) - 1];
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.