Minimum Cost to Connect Two Groups of Points — LeetCode 1595 Python Solution

HardBit ManipulationArrayDynamic ProgrammingBitmaskMatrix
Problem
#1595
Reading time
3 min

The problem

You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2. The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group.

Example

Input
cost = [[15, 96], [36, 2]]
Output
17
Explanation
The optimal way of connecting the groups is:

Python solution

Python
class Solution:
    def connectTwoGroups(self, cost: List[List[int]]) -> int:
        m, n = len(cost), len(cost[0])
        f = [[inf] * (1 << n) for _ in range(m + 1)]
        f[0][0] = 0
        for i in range(1, m + 1):
            for j in range(1 << n):
                for k in range(n):
                    if (j >> k & 1) == 0:
                        continue
                    c = cost[i - 1][k]
                    x = min(f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]) + c
                    f[i][j] = min(f[i][j], x)
        return f[m][-1]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1595. Minimum Cost to Connect Two Groups of Points is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1595. Minimum Cost to Connect Two Groups of Points?
LeetCode 1595. Minimum Cost to Connect Two Groups of Points is rated Hard on LeetCode.
What topics does LeetCode 1595. Minimum Cost to Connect Two Groups of Points cover?
LeetCode 1595. Minimum Cost to Connect Two Groups of Points is tagged Bit Manipulation, Array, Dynamic Programming, Bitmask and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview