Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Level of Each Node

Medium Acceptance 74.21% Points 30

You are given an undirected graph and a source vertex. Your task is to determine the level of every vertex using Breadth First Search (BFS).

The level of a vertex is the minimum number of edges required to reach it from the source vertex.

Return -1 for vertices that are unreachable from the source.

Examples
Example 1

image Input: V = 5, edges = [[0,1],[0,2],[1,3],[2,4]], source = 0
Output: [0,1,1,2,2]
Explanation: Each value represents the minimum distance from the source vertex.

Example 2

image Input: V = 3, edges = [[0,1]], source = 0
Output: [0,1,-1]
Explanation: Vertex 2 is unreachable from the source.

Example 3

image Input: V = 1, edges = [], source = 0
Output: [0]
Explanation: The source vertex is at level 0.

Constraints
    • 1 = V = 105
    • 0 = E = 2 × 105
Topics
Graph
Companies
Oracle Paypal
Added 15 Aug 2026 74.21% acceptance
Ln 1, Col 1Sign in to save your code
5 4
0 1
0 2
1 3
2 4
0
0 1 1 2 2