Minimum Edges to Connect All Components
Updated
Problem statement
A country has n cities numbered from 0 through n - 1. The array edges describes existing undirected roads, where each pair [u, v] connects cities u and v.
You may add a road between any two different cities. Return the minimum number of new roads needed so that every city is reachable from every other city.
If the current graph has k connected components, joining those components requires exactly k - 1 new roads.
Function
minEdgesToConnect(n: int, edges: int[][]) → intExamples
Example 1
n = 4edges = [[0,1],[2,3]]return = 1The graph has two connected components. One new road between them makes the whole country connected.
Example 2
n = 5edges = [[0,1],[1,2],[3,4]]return = 1Cities 0, 1, and 2 form one component, while cities 3 and 4 form another.
Example 3
n = 4edges = []return = 3Every city starts as its own component, so connecting four components needs three new roads.
Constraints
1 ≤ n ≤ 100,0000 ≤ edges.length ≤ 200,000edges[i].length = 20 ≤ edges[i][0], edges[i][1] < n- Every existing edge connects two different cities.
More InMobi Onsite Interview questions
- Russian Doll EnvelopesONSITE INTERVIEW · Seen Jul 2026
- Minimum and Maximum with Optimal ComparisonsONSITE INTERVIEW · Seen Dec 2025
- Shortest Path Visiting All NodesONSITE INTERVIEW · Seen Sep 2025
- Maximum Sum of Non-Adjacent Tree NodesONSITE INTERVIEW · Seen Jan 2022
- Word SquaresONSITE INTERVIEW · Seen Jan 2022
- Maximum Length Pair ChainONSITE INTERVIEW · Seen Jul 2021
- Top View of a Binary TreeONSITE INTERVIEW · Seen Jul 2021
- Maximum XOR Between Two ArraysONSITE INTERVIEW · Seen May 2021
- Trapping Rain WaterONSITE INTERVIEW · Seen May 2021
- Validate Binary Search TreeONSITE INTERVIEW · Seen May 2021
Similar questions at other companies
- Path Existence in an Undirected GraphBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Evaluate DivisionPlaud · ONSITE INTERVIEW
- Count Friend CirclesOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Dynamic Friendship ConnectivityGoogle · ONSITE INTERVIEWGoogle interview questions
- Radar Barrier CrossingSnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Count Islands from Streaming RowsAmazon · ONSITE INTERVIEW
- Accounts MergeOracle · ONSITE INTERVIEWOracle interview questions
- Reconstruct a Graph into a TreeLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Find All People With SecretIDFC Bank · ONSITE INTERVIEWIDFC Bank interview questions
- Redundant ConnectionMicrosoft · ONSITE INTERVIEWMicrosoft interview questions