Bird
Raised Fist0
Interview Prepgraphs-dfs-bfseasyAmazonGoogle

Find Center of Star Graph

Choose your preparation mode4 modes available
📋
Problem

Imagine a social network where one person is the central hub connecting everyone else directly. Finding this person quickly helps in understanding the network's structure.

Given 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 connected to all other nodes, and no other edges exist. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi. Return the center node of the given star graph.

3 ≤ n ≤ 10^5edges.length == n - 1edges[i].length == 21 ≤ ui, vi ≤ nui != viThe given edges represent a valid star graph
Edge cases: Minimum nodes (n=3) → center is the node connected to the other twoEdges where the first two edges share a common node → that node is centerEdges where the center node is the smallest numbered node
</>
IDE
def findCenter(edges: list[list[int]]) -> int:public int findCenter(int[][] edges)int findCenter(vector<vector<int>>& edges)function findCenter(edges)
def findCenter(edges):
    # Write your solution here
    pass
class Solution {
    public int findCenter(int[][] edges) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int findCenter(vector<vector<int>>& edges) {
    // Write your solution here
    return 0;
}
function findCenter(edges) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: First node of first edgeAssuming the first node in the first edge is always the center without checking the second edge.✅ Return the node common to the first two edges instead of blindly returning the first node.
Wrong: Node with highest frequency but not centerIncorrect frequency counting or not counting both nodes in edges properly.✅ Count both nodes in each edge and return the node with frequency n-1.
Wrong: Smallest node alwaysAssuming center is always the smallest node without checking edges.✅ Check the common node in first two edges regardless of node values.
Wrong: Largest node alwaysAssuming center is always the largest node without checking edges.✅ Check the common node in first two edges regardless of node values.
✓
Test Cases
t1_01basic
Input{"edges":[[1,2],[2,3],[4,2]]}
Expected2

Node 2 is connected to nodes 1, 3, and 4, making it the center of the star.

t1_02basic
Input{"edges":[[3,4],[3,2],[3,1],[3,5]]}
Expected3

Node 3 connects to all other nodes 1, 2, 4, and 5, so it is the center.

t2_01edge
Input{"edges":[[1,2],[1,3]]}
Expected1

Minimum nodes (n=3). Node 1 connects to nodes 2 and 3, so it is the center.

t2_02edge
Input{"edges":[[5,1],[5,2],[5,3],[5,4]]}
Expected5

Center node is the largest numbered node (5) connected to all others.

t2_03edge
Input{"edges":[[2,1],[2,3],[2,4],[2,5]]}
Expected2

Center node is the smallest numbered node (2) connected to all others.

t3_01corner
Input{"edges":[[1,2],[3,2],[4,2],[5,2],[6,2]]}
Expected2

Greedy trap: picking first node of first edge (1) is wrong; center is node 2.

t3_02corner
Input{"edges":[[7,3],[3,1],[3,2],[3,4],[3,5]]}
Expected3

Off-by-one error: center node 3 is not first node in all edges; must check both nodes.

t3_03corner
Input{"edges":[[10,1],[10,2],[10,3],[10,4],[10,5],[10,6],[10,7],[10,8],[10,9]]}
Expected10

Hash map frequency confusion: must not count frequencies incorrectly; center appears n-1 times.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

n=100000 edges; O(n) solution must complete within 2 seconds.

Practice

(1/5)
1. You are given a list of edges representing an undirected graph with n nodes labeled from 0 to n-1. You need to determine if the graph forms a valid tree. Which algorithmic approach guarantees an optimal solution to check both connectivity and absence of cycles efficiently?
easy
A. Use a greedy algorithm that adds edges one by one and checks if the graph remains connected.
B. Apply dynamic programming to count the number of ways to reach each node and detect cycles.
C. Sort edges and use binary search to detect cycles and connectivity.
D. Perform a BFS or DFS traversal to detect cycles and verify that all nodes are connected.

Solution

  1. Step 1: Understand problem requirements

    The problem requires checking if the graph is connected and contains no cycles, which defines a tree.
  2. Step 2: Identify suitable algorithm

    BFS or DFS traversal can detect cycles by tracking visited nodes and parent relationships, and also verify connectivity by ensuring all nodes are visited.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    BFS/DFS simultaneously checks connectivity and cycles efficiently [OK]
Hint: Trees have n-1 edges and no cycles [OK]
Common Mistakes:
  • Assuming greedy edge addition ensures connectivity
  • Using DP which is unrelated here
2. Consider the following Union-Find based code snippet to check if a graph is bipartite. Given the graph adjacency list [[1,3],[0,2],[1,3],[0,2]], what is the return value of isBipartite(graph)?
easy
A. true
B. false
C. Raises an exception
D. null (infinite loop)

Solution

  1. Step 1: Trace union operations for node 0

    Node 0 neighbors: 1 and 3. Union(1,3) is called. Since 1 and 3 are separate, union succeeds.
  2. Step 2: Trace union operations for other nodes

    For node 1 neighbors: 0 and 2. Union(0,2) is called. 0 and 2 are separate, union succeeds. Similarly for node 2 and 3, unions succeed without conflict.
  3. Step 3: Check for conflicts

    However, the union-find approach here incorrectly unions neighbors of the same node, which can cause false positives. The code logic is flawed for bipartite checking.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    The code returns false due to a union conflict, indicating the graph is not bipartite [OK]
Hint: Union-Find returns false only on odd cycle detection [OK]
Common Mistakes:
  • Confusing union arguments order
  • Assuming union returns true on conflict
3. What is the time complexity of the optimal bidirectional BFS approach for the Word Ladder problem, where N is the number of words in the dictionary and L is the length of each word?
medium
A. O(N^2 * L)
B. O(N * 26^L)
C. O(N * L^2)
D. O(N * L * 26)

Solution

  1. Step 1: Identify operations per word

    For each word, we try changing each of its L letters to 26 possible letters, generating up to 26*L neighbors.
  2. Step 2: Consider total words processed

    In worst case, all N words are visited, so total operations are O(N * L * 26).
  3. Step 3: Consider the cost of checking each generated word

    Checking if a generated word is in the dictionary (word_set) can be done in O(1) average, but generating each neighbor involves string slicing which is O(L), so total complexity is O(N * L^2).
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Each neighbor generation involves O(L) slicing, repeated for O(N * L * 26) neighbors, resulting in O(N * L^2) complexity [OK]
Hint: Each word generates O(L*26) neighbors, each neighbor generation costs O(L) due to slicing [OK]
Common Mistakes:
  • Confusing exponential 26^L with linear 26*L
  • Assuming quadratic N^2 due to pairwise checks
  • Ignoring string slicing cost in complexity
4. Suppose the problem is modified so that you can only move in 4 directions (up, down, left, right) instead of 8. Which of the following statements about the shortest path algorithm is true?
hard
A. Greedy Best-First Search guarantees shortest path with 4-direction moves
B. Bidirectional BFS still finds the shortest path, but the path length may be longer due to restricted moves
C. DFS with backtracking becomes optimal since fewer directions reduce complexity
D. Dynamic Programming is required to handle the reduced movement directions

Solution

  1. Step 1: Understand movement restriction impact

    Reducing to 4 directions limits possible paths, potentially increasing shortest path length.
  2. Step 2: Evaluate algorithm suitability

    Bidirectional BFS still finds shortest path efficiently; DFS and greedy do not guarantee shortest path.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bidirectional BFS adapts to movement constraints, still optimal [OK]
Hint: Bidirectional BFS adapts to movement constraints [OK]
Common Mistakes:
  • Assuming DFS or greedy become optimal
  • Thinking DP is needed for movement changes
5. Suppose the Surrounded Regions problem is modified so that the board can be very large and the number of 'O's connected to the boundary is small. Which of the following modifications to the BFS approach would improve space efficiency without sacrificing correctness?
hard
A. Use DFS with recursion instead of BFS to avoid storing a large queue.
B. Only enqueue boundary 'O's and avoid marking visited cells, relying on board state changes.
C. Use BFS but mark visited cells in-place and prune early when no new 'O's are found.
D. Run BFS from every 'O' cell to ensure all regions are checked independently.

Solution

  1. Step 1: Consider space usage of BFS queue

    BFS queue can grow large if many 'O's are connected; marking visited in-place helps avoid revisiting.
  2. Step 2: Prune BFS early when no new 'O's are found

    This reduces unnecessary queue growth and improves space efficiency without losing correctness.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    In-place marking plus pruning optimizes BFS space [OK]
Hint: In-place marking and pruning reduce BFS queue size [OK]
Common Mistakes:
  • Using DFS recursion can cause stack overflow on large boards.
  • Not marking visited cells causes infinite loops or revisits.
  • Running BFS from every 'O' is inefficient and unnecessary.
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard