#1761

Minimum Degree of a Connected Trio in a Graph

Hard
Graph TheoryEnumerationGraph TraversalAdjacency ListDegree Calculation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + e)
Space
O(1)
O(n)
💡

Intuition

Time O(n + e)Space O(n)

The optimal solution uses a more structured approach by leveraging the properties of degrees and adjacency to efficiently find connected trios without checking every combination explicitly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create an adjacency list to represent the graph.
  2. 2Step 2: For each node, calculate its degree and store it.
  3. 3Step 3: For each edge, check if both endpoints have common neighbors to form a trio.
  4. 4Step 4: Calculate the degree of the trio using the formula: degree(u) + degree(v) + degree(w) - 6.
  5. 5Step 5: Keep track of the minimum degree found.
solution.py17 lines
1def minTrioDegree(n, edges):
2    from collections import defaultdict
3    graph = defaultdict(set)
4    degree = [0] * (n + 1)
5    for u, v in edges:
6        graph[u].add(v)
7        graph[v].add(u)
8        degree[u] += 1
9        degree[v] += 1
10    min_degree = float('inf')
11    for u in range(1, n + 1):
12        for v in graph[u]:
13            for w in graph[u]:
14                if v < w and w in graph[v]:
15                    trio_degree = degree[u] + degree[v] + degree[w] - 6
16                    min_degree = min(min_degree, trio_degree)
17    return min_degree if min_degree != float('inf') else -1

Complexity note: The time complexity is O(n + e) where e is the number of edges, as we traverse the edges to build the graph and then check for trios. The space complexity is O(n) due to the adjacency list and degree array.

  • 1Understanding the structure of the graph is crucial for identifying connected trios.
  • 2Using degrees effectively helps in calculating the minimum degree quickly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.