Question bank › Union Find
Dsa Union Find Medium

Galaxy Collapse

There are N stars, each with a specific mass. Stars cluster into galaxies. When two galaxies merge, their total mass is the sum of the masses of all stars in both. If a galaxy's total mass exceeds a safety Limit L, it 'collapses' into a black hole cluster. Once a galaxy collapses, it remains collapsed even if it merges with other galaxies. Calculate how many stars are in collapsed galaxies after M merges. Input Format: Line 1: N (stars), M (merges), L (mass limit). Line 2: N integers representing the mass of each star (0 to N-1). Next M lines: Two integers u and v (a merge between the galaxy containing u and the galaxy containing v). Output Format: A single integer: total number of stars in collapsed galaxies. Example: Input: 4 2 10 5 6 3 2 0 1 2 3 Output: 2 Explanation: Masses: [5, 6, 3, 2]. Limit: 10. Merge (0,1): Total mass 5+6=11. 11 > 10, so galaxy {0,1} collapses. (2 stars) Merge (2,3): Total mass 3+2=5. 5 <= 10, not collapsed. Total stars in collapsed: 2.

Key concepts

union_findweight_summing

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of Praxari's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.