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.
Minimum Cost to Connect Two Groups of Points — Solution
The key insight is to use dynamic programming with bitmasks to efficiently track which points in the smaller group are connected. The optimal approach uses bottom-up DP with state transitions, achieving O(m × 2^n × n) time complexity. We precompute minimum connection costs and handle unconnected points in the final step.
Common Approaches
✓
Brute Force - Try All Connections
⏱️ Time: O(3^(m×n))
Space: O(m×n)
Try every possible combination of connections where each point in both groups has at least one connection. This involves exponential possibilities since each point in group1 can connect to any subset of group2 points.
Dynamic Programming with Memoization
⏱️ Time: O(m × 2^n × n)
Space: O(m × 2^n)
Use recursive approach with memoization where we track which points in group1 we've processed and which points in group2 are already connected using bitmasks. This reduces redundant calculations significantly.
Optimized DP with Bottom-Up Approach
⏱️ Time: O(m × 2^n × n)
Space: O(2^n)
Use bottom-up dynamic programming where dp[i][mask] represents minimum cost to connect first i points of group1 such that mask represents which points in group2 are connected. This eliminates recursion overhead and provides cleaner state transitions.
Brute Force - Try All Connections — Algorithm Steps
Generate all possible connection combinations
Check if each combination satisfies connectivity requirements
Calculate cost and track minimum
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Generate Combinations
Try every possible connection between groups
2
Validate Connectivity
Check if all points are connected
3
Track Minimum
Keep track of minimum valid cost
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_NODES 20
#define MAX_STATES 1000000
typedef struct {
int i, mask, value;
} DPEntry;
static DPEntry dp[MAX_STATES];
static int dpSize = 0;
int findDP(int i, int mask) {
for (int k = 0; k < dpSize; k++) {
if (dp[k].i == i && dp[k].mask == mask) {
return dp[k].value;
}
}
return -1;
}
void setDP(int i, int mask, int value) {
if (dpSize < MAX_STATES) {
dp[dpSize].i = i;
dp[dpSize].mask = mask;
dp[dpSize].value = value;
dpSize++;
}
}
int solve(int i, int mask, int** cost, int m, int n) {
int cached = findDP(i, mask);
if (cached != -1) {
return cached;
}
if (i == m) {
if (mask == (1 << n) - 1) {
setDP(i, mask, 0);
return 0;
} else {
setDP(i, mask, INT_MAX);
return INT_MAX;
}
}
int result = INT_MAX;
// Try all possible subsets of group2 points to connect point i to
// Point i must connect to at least one point in group2
for (int subset = 1; subset < (1 << n); subset++) { // subset must be non-empty
int cost_for_subset = 0;
int new_mask = mask;
for (int j = 0; j < n; j++) {
if (subset & (1 << j)) {
cost_for_subset += cost[i][j];
new_mask |= (1 << j);
}
}
int subResult = solve(i + 1, new_mask, cost, m, n);
if (subResult != INT_MAX) {
int total = cost_for_subset + subResult;
if (total < result) {
result = total;
}
}
}
setDP(i, mask, result);
return result;
}
int solution(int** cost, int m, int n) {
// dp[i][mask] = min cost to ensure first i points from group1 are connected
// and group2 points in mask are connected
dpSize = 0;
return solve(0, 0, cost, m, n);
}
int main() {
static char line[10000];
fgets(line, sizeof(line), stdin);
// Parse JSON array
int** cost = NULL;
int m = 0, n = 0;
// Count rows by counting inner arrays
char* p = line;
int bracket_depth = 0;
while (*p) {
if (*p == '[') {
bracket_depth++;
if (bracket_depth == 2) {
m++;
}
} else if (*p == ']') {
bracket_depth--;
}
p++;
}
cost = malloc(m * sizeof(int*));
// Parse each row
p = line;
int rowIdx = 0;
bracket_depth = 0;
while (*p && rowIdx < m) {
// Find start of inner array
while (*p && !(bracket_depth == 1 && *p == '[')) {
if (*p == '[') bracket_depth++;
else if (*p == ']') bracket_depth--;
p++;
}
if (!*p) break;
// Now at start of inner array, skip '['
p++;
// Parse numbers in this row
static int rowData[MAX_NODES];
int rowSize = 0;
while (*p && *p != ']') {
// Skip whitespace and commas
while (*p == ' ' || *p == ',') p++;
if (*p == ']') break;
// Parse number
char* endptr;
rowData[rowSize++] = (int)strtol(p, &endptr, 10);
p = endptr;
}
if (rowIdx == 0) n = rowSize;
cost[rowIdx] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++) {
cost[rowIdx][j] = rowData[j];
}
rowIdx++;
// Skip the closing ']' of inner array
if (*p == ']') p++;
}
int result = solution(cost, m, n);
printf("%d\n", result);
// Free memory
for (int i = 0; i < m; i++) {
free(cost[i]);
}
free(cost);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(3^(m×n))
Each cell can be unconnected, connected from group1, or connected from group2
n
2n
⚠ Quadratic Growth
Space Complexity
O(m×n)
Space to store current connection state during recursion
n
2n
⚠ Quadratic Space
28.5K Views
MediumFrequency
~35 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.