Problem solution · Python

Minimum Incompatibility

Minimum Incompatibility: 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
70 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 Minimum Incompatibility, 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

  • 70 lines of Python from the credited upstream file 1681.py.
  • The implementation visibly relies on sequence storage, 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 codeMinimum Incompatibility · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def __init__(self):    self.MAX_NUM = 16   def minimumIncompatibility(self, nums: list[int], k: int) -> int:    MAX_COMPATIBILITY = (16 - 1) * (16 // 2)    n = len(nums)    subsetSize = n // k    maxMask = 1 << n    incompatibilities = self._getIncompatibilities(nums, subsetSize)     # dp[i] := the minimum possible sum of incompatibilities of the subset    # of numbers represented by the bitmask i    dp = [MAX_COMPATIBILITY] * maxMask    dp[0] = 0     for mask in range(1, maxMask):      # The number of 1s in `mask` isn't a multiple of `subsetSize`.      if mask.bit_count() % subsetSize != 0:        continue      # https://cp-algorithms.com/algebra/all-submasks.html      submask = mask      while submask > 0:        if incompatibilities[submask] != -1:  # valid submask          dp[mask] = min(dp[mask], dp[mask - submask] +                         incompatibilities[submask])        submask = (submask - 1) & mask     return dp[-1] if dp[-1] != MAX_COMPATIBILITY else -1   def _getIncompatibilities(      self,      nums: list[int],      subsetSize: int,  ) -> list[int]:    """    Returns an incompatibilities array where    * incompatibilities[i] := the incompatibility of the subset of numbers      represented by the bitmask i    * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not      `subsetSize`    """    maxMask = 1 << len(nums)    incompatibilities = [-1] * maxMask    for mask in range(maxMask):      if mask.bit_count() == subsetSize and self._isUnique(nums, mask, subsetSize):        incompatibilities[mask] = self._getIncompatibility(nums, mask)    return incompatibilities   def _isUnique(self, nums: list[int], mask: int, subsetSize: int) -> bool:    """Returns True if the numbers selected by `mask` are unique."""    used = 0    for i, num in enumerate(nums):      if mask >> i & 1:        used |= 1 << num    return used.bit_count() == subsetSize   def _getIncompatibility(self, nums: list[int], mask: int) -> int:    """    Returns the incompatibility of the selected numbers represented by the    `mask`.    """    mn = self.MAX_NUM    mx = 0    for i, num in enumerate(nums):      if mask >> i & 1:        mx = max(mx, num)        mn = min(mn, num)    return mx - mn 

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 ↗