Min Cost to Connect All Points

MediumGraphsminimum spanning tree

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given points, where points[i] = [x, y] is a distinct point on a 2D plane. Connecting two points costs their **Manhattan distance**, |x1 - x2| + |y1 - y2|. Return the minimum total cost to connect all points so that every pair is joined by exactly one simple path (in other words, the cost of a minimum spanning tree). A single point costs 0. Every pair of points may be connected, so the graph is complete; an O(n²) Prim's algorithm fits comfortably.

Examples

Input: points = [[0,0],[4,0],[0,3],[4,3]]
Output: 10
Use edges (0,0)-(0,3) cost 3, (0,0)-(4,0) cost 4 and (4,0)-(4,3) cost 3.
Input: points = [[0,0],[1,1],[3,0]]
Output: 5
Connect (0,0)-(1,1) for 2 and (1,1)-(3,0) for 3.

Constraints

  • 1 <= points.length <= 1000
  • -10^5 <= x, y <= 10^5
  • All points are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.