Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1761. Minimum Degree of a Connected Trio in a Graph

Graph

Explanation:

To solve this problem, we can iterate through all possible connected trios and calculate their degrees. We can then keep track of the minimum degree found so far.

  1. Create a graph representation using an adjacency list.
  2. Iterate through all possible trios of nodes.
  3. For each trio, calculate the degree by counting the number of edges outside the trio.
  4. Update the minimum degree found so far.
  5. Return the minimum degree as the result.

Time Complexity: O(n^3), where n is the number of nodes.

Space Complexity: O(n^2) for the adjacency list.

:

class Solution {
    public int minTrioDegree(int n, int[][] edges) {
        int[] degree = new int[n + 1];
        boolean[][] connected = new boolean[n + 1][n + 1];
        
        for (int[] edge : edges) {
            int u = edge[0], v = edge[1];
            degree[u]++;
            degree[v]++;
            connected[u][v] = true;
            connected[v][u] = true;
        }
        
        int minDegree = Integer.MAX_VALUE;
        
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                if (connected[i][j]) {
                    for (int k = j + 1; k <= n; k++) {
                        if (connected[i][k] && connected[j][k]) {
                            int trioDegree = degree[i] + degree[j] + degree[k] - 6;
                            minDegree = Math.min(minDegree, trioDegree);
                        }
                    }
                }
            }
        }
        
        return minDegree == Integer.MAX_VALUE ? -1 : minDegree;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.