↓Skip to main content
  1. LeetCode/

LeetCode 1791: Find Center of Star Graph

·1 min· ·
LeetCode Easy Graph
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-22

  • Submissions: Accepted (first try)

Approach
#

A star’s center connects to every other node, so every edge contains it. The endpoint shared by the first two edges is the center, in O(1) with no graph building or degree counting (BFS covers graph basics).

My Solution
#

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        a, b = edges[0]
        return a if a in edges[1] else b

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • Counting degrees works too, but two edges suffice.

Interview Explanation
#

The center appears on every edge, so the endpoint shared by the first two edges is the answer. Time O(1).

Related

LeetCode 997: Find the Town Judge
·2 mins
LeetCode Easy Array Hash-Table Graph
LeetCode 997 note: the judge is trusted by the other n - 1 people and trusts nobody, so in-degree minus out-degree equals n - 1
LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 2331: Evaluate Boolean Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 2331 note: leaves are 0 or 1 and internal nodes are 2 for OR and 3 for AND, evaluated in post-order
LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1379 note: walk both trees in lockstep; when the original reaches target, the clone’s node at the same position is the answer, comparing node identity
LeetCode 1108: Defanging an IP Address
·1 min
LeetCode Easy String
LeetCode 1108 note: replace every . with [.]
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words