Node Degree

Node Degree

In an undirected graph, the degree of a node is the number of edges touching it. Given the graph as an adjacency list and a node, return that node's degree.

nodeDegree(graph, node)

Input format: edges | node. Edges are a,b pairs separated by spaces; each builds an undirected connection. For example a,b a,c b,d | a.

Examples

edges a,b a,c b,d, node a   // → 2   (a–b, a–c)
edges a,b a,c b,d, node b   // → 2   (a–b, b–d)
edges a,b, node c           // → 0

Walkthrough

Thinking it through

This is a warm-up for reading graph data. An adjacency list stores a graph as a mapping from each node to the nodes it directly connects to. For an undirected graph, every edge is recorded twice — once in each node's neighbour list — since the connection goes both ways.

What "degree" actually means

The degree of a node is just a count: how many edges touch it. In an adjacency list, that count is already sitting there — it's the length of that node's neighbour list. No scanning the whole graph, no traversal at all. The structure already grouped each node's connections; you just measure how many there are.

Handling nodes that aren't in the map

What if you're asked for the degree of a node that never appears as an edge endpoint? It simply isn't a key in the adjacency list. Rather than an error, the correct answer is 0 — no recorded edges means no neighbours. Your solution should treat a missing key as an empty list, not crash.

Why this is worth internalizing

This simple problem sets the mental model for every harder graph problem ahead: a graph is a mapping from identity (a node) to relationships (its neighbours). A question about one node is usually a lookup; a question about the whole graph (reachability, components, cycles) needs traversal. Spotting which kind you're facing — lookup or walk-the-structure — is the first judgment call on any graph problem, and this one is purely the former.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.