|
| 1 | +# [1791. Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Intuition and Approach to Solving the Find Center Problem" |
| 6 | +summary: "An explanation of the intuition, approach, and complexities involved in solving the find center problem in graph theory, along with the implementation in JavaScript." |
| 7 | +date: "2024年06月27日" |
| 8 | +modifiedDate: "2024年06月27日" |
| 9 | +tags: ["Graph Theory", "Algorithm", "JavaScript"] |
| 10 | +slug: "intuition-and-approach-to-solving-the-find-center-problem" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | +# Intuition |
| 15 | + |
| 16 | +The problem involves finding the center of a star graph. A star graph has one central node connected to all other nodes. The intuition is that in a star graph, the central node will appear in every edge. |
| 17 | + |
| 18 | +# Approach |
| 19 | + |
| 20 | +To solve this problem, consider the first two edges of the given list. The center of the star graph must be one of the nodes in the first edge and must also appear in the second edge. By comparing the nodes in the first and second edges, we can identify the center node. |
| 21 | + |
| 22 | +# Complexity |
| 23 | + |
| 24 | +## Time complexity: |
| 25 | + |
| 26 | +The solution only checks the first two edges and performs a constant number of operations, resulting in a time complexity of $$O(1)$$. |
| 27 | + |
| 28 | +## Space complexity: |
| 29 | + |
| 30 | +The solution uses a constant amount of extra space, resulting in a space complexity of $$O(1)$$. |
| 31 | + |
| 32 | +# Code |
| 33 | + |
| 34 | +```javascript |
| 35 | +/** |
| 36 | + * @param {number[][]} edges |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +function findCenter(edges) { |
| 40 | + // Destructure the first edge to get the two nodes |
| 41 | + const [a, b] = edges[0]; |
| 42 | + |
| 43 | + // Destructure the second edge to get the two nodes |
| 44 | + const [c, d] = edges[1]; |
| 45 | + |
| 46 | + // Check which node from the first edge matches either node in the second edge |
| 47 | + if (a === c || a === d) { |
| 48 | + return a; |
| 49 | + } |
| 50 | + return b; |
| 51 | +} |
| 52 | +``` |
0 commit comments