Skip to the code
cf.
+25 XP

#413 Group Users by Degrees of Separation

medium

A network explorer groups users by how far they are from a chosen user. Users are numbered 0 to n - 1, and edges[i] = [a, b] means a and b are connected (both ways).

Write groupByDistance(n, edges, start) that returns a list of groups. Group d holds every user whose shortest distance from start is exactly d, sorted ascending. Group 0 is [start]. Users that can't be reached from start appear in no group.

Example 1

Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,3],[3,4]], start = 0
Output: [[0],[1,2],[3],[4]]

1 and 2 are one step away, 3 is two steps away, 4 is three. User 5 can't be reached, so it's left out.

Example 2

Input: n = 1, edges = [], start = 0
Output: [[0]]

Only the start itself, at distance 0.

Constraints

  • 1 <= n <= 10000
  • 0 <= edges.length <= 50000
  • 0 <= a, b, start < n, a !== b
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).