↻one more pass.
Advanced graphs · Medium

Min Cost to Connect All Points: the idea to remember.

Connect all 2D points with minimum total Manhattan edge cost.

Solve on LeetCode ↗

The core insight

Grow a connected set by repeatedly choosing its cheapest edge to an unvisited point.

Why it works

The cut property guarantees the cheapest edge crossing from the connected set is safe for a minimum spanning tree.

The mistake to avoid

Skip stale heap entries for already visited points. Use Manhattan, not Euclidean distance.

Time: O(n² log n)Space: O(n²) heap edges

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Grow a connected set by repeatedly choosing its cheapest edge to an unvisited point.
public int minCostConnectPoints(int[][] points) {
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); 
    pq.offer(new int[] { 0, 0 });
    int len = points.length;
    Set<Integer> visited = new HashSet<>();
    int cost = 0;


    while (visited.size() < len) {
        int[] arr = pq.poll();

        int weight = arr[0];
        int currNode = arr[1];

        if (visited.contains(currNode)) continue;

        visited.add(currNode);
        cost += weight;

        for (int nextNode = 0; nextNode < len; nextNode++) {
            if (!visited.contains(nextNode)) {
                int nextWeight =
                    Math.abs(points[nextNode][0] - points[currNode][0]) +
                    Math.abs(points[nextNode][1] - points[currNode][1]);
                pq.offer(new int[] { nextWeight, nextNode });
            }
        }
    }

    return cost;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.