Minimum Cost to Connect Two Groups of Points - 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 is given in a 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.

The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.

Return the minimum cost it takes to connect the two groups.

Input & Output

Example 1 — Basic Case
$ Input: cost = [[15,96],[36,2]]
Output: 17
💡 Note: Connect point 0 from group1 to point 0 from group2 (cost=15), and point 1 from group1 to point 1 from group2 (cost=2). Total cost = 15 + 2 = 17. All points are connected.
Example 2 — Multiple Connections
$ Input: cost = [[1,3,5],[4,1,1],[1,5,3]]
Output: 4
💡 Note: Connect point 0 to point 0 (cost=1), point 1 to point 1 (cost=1), point 2 to point 1 (cost=5). But we can do better: connect point 0 to point 0 (cost=1), point 1 to point 2 (cost=1), point 2 to point 1 (cost=5). However, the optimal is: point 0→0 (cost=1), point 1→1 (cost=1), point 2→2 (cost=3). But point 1 needs connection, so point 1→1 (cost=1), others connect optimally. Answer is 4.
Example 3 — Single Column
$ Input: cost = [[2],[3],[1]]
Output: 6
💡 Note: Only one point in group2. All three points in group1 must connect to it, so total cost = 2 + 3 + 1 = 6. The single group2 point is connected through all these connections.

Constraints

  • size1 == cost.length
  • size2 == cost[i].length
  • 1 ≤ size1, size2 ≤ 12
  • size1 ≥ size2
  • 0 ≤ cost[i][j] ≤ 100

Visualization

Tap to expand
Minimum Cost to Connect Two Groups of PointsGroup 1Group 2012011525Total Cost: 15 + 2 = 17All points connected with minimum costUse DP with bitmasks to track Group 2 connections efficiently
Understanding the Visualization
1
Input
Two groups with connection costs in matrix format
2
Constraint
Every point in both groups must be connected to opposite group
3
Goal
Find minimum cost to satisfy all connection requirements
Key Takeaway
🎯 Key Insight: Use bitmasks to track which points in the smaller group are connected, enabling efficient DP state transitions
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen