#1655
Distribute Repeating Integers
HardArrayHash TableDynamic ProgrammingBacktrackingBit ManipulationCountingBitmaskHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
The optimal solution uses a backtracking approach to efficiently explore the distribution of integers. By counting the frequencies of each integer and trying to satisfy each customer's order one by one, we can prune unnecessary checks and find a valid distribution faster.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each unique integer in nums.
- 2Step 2: Sort the quantity array in descending order to prioritize larger orders first.
- 3Step 3: Use a backtracking function to attempt to assign integers to each customer, checking if the current assignment can satisfy the quantity requirements.
solution.py19 lines
1# Full working Python code
2from collections import Counter
3
4def canDistribute(nums, quantity):
5 freq = Counter(nums)
6 unique_numbers = sorted(freq.values(), reverse=True)
7 quantity.sort(reverse=True)
8 return backtrack(unique_numbers, quantity, 0)
9
10def backtrack(unique_numbers, quantity, index):
11 if index == len(quantity):
12 return True
13 for i in range(len(unique_numbers)):
14 if unique_numbers[i] >= quantity[index]:
15 unique_numbers[i] -= quantity[index]
16 if backtrack(unique_numbers, quantity, index + 1):
17 return True
18 unique_numbers[i] += quantity[index]
19 return Falseℹ
Complexity note: The time complexity is driven by the backtracking approach, where n is the number of unique integers and m is the number of customers. Each customer may require a different number of checks, but we avoid unnecessary checks through pruning.
- 1Count the frequencies of each number to understand how many can be assigned.
- 2Sort the quantity array to prioritize larger orders, which helps in backtracking.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.