DEV Community

Cover image for LeetCode — 1791. Find Center of Star Graph
Ben Pereira
Ben Pereira

Posted on

LeetCode — 1791. Find Center of Star Graph

It’s an easy problem with the description being:

There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.

You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.

The first thing before starting to solve this issue is to understand a star graph, best way to get into it is looking into different types:

As you can see in this image, the idea of the star graph is that there is multiple points and a center piece. With that in mind we can always assume that the second array in the edges will be the one related to the center, but the exact number is still something that we need to identify based on validations.

With that in mind then is just about comparing the numbers and giving the right one:

class Solution { public int findCenter(int[][] edges) { return edges[0][1] == edges[1][0] || edges[0][1] == edges[1][1] ? edges[0][1] : edges[0][0]; } } 
Enter fullscreen mode Exit fullscreen mode

Runtime: 0ms, faster than 100.00% of Java online submissions.

Memory Usage: 72.20 MB, less than 61.83% of Java online submissions.

If for some reason the items were mixed then would be a bit more trouble to look for the center piece and compare with the respective one (meaning we would have to iterate it further), but that’s not the case here.

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

Top comments (0)