Minimum Degree of a Connected Trio in a Graph - Problem

You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.

A connected trio is a set of three nodes where there is an edge between every pair of them.

The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.

Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.

Input & Output

Example 1 — Basic Connected Trio
$ Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]
Output: 3
💡 Note: There are exactly 3 trios: (1,2,3), (1,2,4), and (2,3,5). The trio (1,2,3) has degree 3 (node 1 connects to 4, node 2 connects to 5, node 3 connects to 6), which is minimum.
Example 2 — No Connected Trios
$ Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7]]
Output: -1
💡 Note: No set of 3 nodes forms a complete triangle where every pair is connected.
Example 3 — Perfect Triangle
$ Input: n = 3, edges = [[1,2],[2,3],[1,3]]
Output: 0
💡 Note: The only trio is (1,2,3) and all three nodes only connect to each other, so external degree is 0.

Constraints

  • 2 ≤ n ≤ 400
  • edges.length ≤ n * (n-1) / 2
  • edges[i].length == 2
  • 1 ≤ ui, vi ≤ n
  • ui != vi
  • There are no repeated edges

Visualization

Tap to expand
Minimum Degree of Connected Trio INPUT 1 2 3 4 5 6 TRIO n = 6 edges = [[1,2],[1,3],[3,2], [4,1],[5,2],[3,6]] Adjacency Set: 1:{2,3,4} 2:{1,3,5} 3:{1,2,6} 4:{1} 5:{2} 6:{3} ALGORITHM STEPS 1 Build Adjacency Set Store neighbors in HashSet for O(1) lookup 2 Find All Trios For each edge (u,v), find common neighbor w 3 Calculate Degree degree = deg(u)+deg(v) +deg(w) - 6 4 Track Minimum Update minDegree if current is smaller Trio {1,2,3} Calculation: deg(1)=3, deg(2)=3, deg(3)=3 Total edges = 3+3+3 = 9 Internal edges = 6 External = 9 - 6 = 3 Degree = 3 FINAL RESULT Found Trio: 1 2 3 to 5 to 4 to 6 OUTPUT 3 Minimum degree of trio = 3 [OK] Key Insight: Using adjacency sets enables O(1) neighbor lookup. For each edge (u,v), we check common neighbors w to form trios. The degree formula (deg(u)+deg(v)+deg(w)-6) subtracts the 6 internal edge endpoints within the trio (3 edges x 2 endpoints each), leaving only external connections. TutorialsPoint - Minimum Degree of a Connected Trio in a Graph | Optimized with Adjacency Set
Asked in
Facebook 35 Google 28 Amazon 22
33.0K Views
Medium Frequency
~25 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