Problem solution · Python

Distribute Repeating Integers

Distribute Repeating Integers: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
40 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Distribute Repeating Integers, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 40 lines of Python from the credited upstream file 1655.py.
  • The implementation visibly relies on sequence storage, hash lookup, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDistribute Repeating Integers · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def canDistribute(self, nums: list[int], quantity: list[int]) -> bool:    freqs = list(collections.Counter(nums).values())    # validDistribution[i][j] := True if it's possible to distribute the i-th    # freq into a subset of quantity represented by the bitmask j    validDistribution = self._getValidDistribution(freqs, quantity)    n = len(freqs)    m = len(quantity)    maxMask = 1 << m    # dp[i][j] := true if it's possible to distribute freqs[i..n), where j is    # the bitmask of the selected quantity    dp = [[False] * maxMask for _ in range(n + 1)]    dp[n][maxMask - 1] = True     for i in range(n - 1, -1, -1):      for mask in range(maxMask):        dp[i][mask] = dp[i + 1][mask]        availableMask = ~mask & (maxMask - 1)        submask = availableMask        while submask > 0:          if validDistribution[i][submask]:            dp[i][mask] = dp[i][mask] or dp[i + 1][mask | submask]          submask = (submask - 1) & availableMask     return dp[0][0]   def _getValidDistribution(self, freqs: list[int],                            quantity: list[int]) -> list[list[bool]]:    maxMask = 1 << len(quantity)    validDistribution = [[False] * maxMask for _ in range(len(freqs))]    for i, freq in enumerate(freqs):      for mask in range(maxMask):        if freq >= self._getQuantitySum(quantity, mask):          validDistribution[i][mask] = True    return validDistribution   def _getQuantitySum(self, quantity: list[int], mask: int) -> int:    """Returns the sum of the selected quantity represented by `mask`."""    return sum(q for i, q in enumerate(quantity) if mask >> i & 1) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗