DSA Factory
Free Union-find lessonsUnion-find · Stage 2 · Mastery · Step 1

How far would a rumor spread?

Build the final groups first, then answer a size query for each of several starting points. About 10 minutes.

Build first, then answer

This mastery step combines two ideas you already have: keeping each group's size at its leader, and answering several questions against one finished set of groups.

A good habit for problems like this: finish building everything before you answer anything. Then each question is a single lookup: find the person's leader and read the group's size.

Build first: every merge before any question.
6 people who know 0–1, 2–3, 1–3 · rumours start at 0 and 4
0123size 44size 15size 1
answers
[]

Build first: merge along every connection, keeping each group's size at its leader. Only then answer questions.

Move 1 of 3
Quick check

Two rumour starters are in the same group of 4 people. What do you return for them?

  1. A4 and 4
  2. BTheir own numbers
Show the answer

4 and 4. They share a group, so both rumours reach the same 4 people.

Your problem

How far would a rumor spread?

There are n people, numbered 0 to n - 1, and edges lists pairs [a, b] meaning a and b know each other, processed in order (knowing is symmetric and travels through a chain of acquaintances, so it works exactly like a union-find merge). For each person in starters, if they started a rumor, return how many people (including themselves) would eventually hear it: the size of their final group. Return the answers in the same order as starters.

Example
n = 5, edges = [[0, 1], [1, 2], [3, 4]], starters = [0, 3] → [3, 2]

1 ≤ n ≤ 100,000 · 0 ≤ edges.length ≤ 100,000 · 1 ≤ starters.length ≤ 100,000 · edges[i] has two different node numbers, each 0 ≤ x < n · every starter is 0 ≤ x < n

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve