Degree of every vertex
Standard · Write code · about 8 min
graph is undirected with vertices 0 to n - 1. Return an array whose entry v is the degree of vertex v.
A self-loop [v, v] touches v twice, so it adds 2. Parallel edges each count.
Example 1
Input:
[{"n":5,"edges":[[0,1],[0,2],[1,2],[1,3],[2,3],[3,4]],"directed":false}]
Output:
[2,3,3,3,1]
Vertex 1 touches edges 0-1, 1-2 and 1-3.
Example 2
Input:
[{"n":4,"edges":[[0,1],[0,2],[0,3]],"directed":false}]
Output:
[3,1,1,1]
A star: the centre touches every edge.
Constraints
- 1 ≤ n ≤ 1,000
- 0 ≤ edges.length ≤ 2,000
- 0 ≤ u, v < n
Learn the idea first: Graphs: vertices, edges, directed, weighted, degree, paths, a visual lesson.
More Graphs: vertices, edges, directed, weighted, degree, paths problems
- Count the degrees Warm-up
- Path or cycle? Standard
- Is this sequence a path? Standard
- In-degree and out-degree Standard
- The handshake lemma Challenge