Journey to the Moon

Pattern: Connected components and islands

medium

Astronaut pairs from the same country join into groups. Count pairs of astronauts from different countries: go through the groups, and for each new group of size s add s times the number of astronauts counted so far. The answer can be large.

The problem

n astronauts are numbered 0 to n - 1. Each pair in the list is from the same country. Return how many pairs of astronauts from different countries can be chosen. An astronaut in no pair is a country alone.

Think first

  • What is a country in graph terms?
  • How many pairs come from two countries of sizes a and b?
  • How do you add up all cross pairs without a double loop?

Hints

    Brute force, and why it fails

    Compare every pair of astronauts: O(n²).

    The key insight

    Grouping first and then counting cross pairs with a running sum is linear in the number of astronauts.

    Dry run

    sizes3 2

    n = 5, same-country pairs 0-1, 2-3, 0-4. Groups: {0, 1, 4}, {2, 3}.

    Step 1 of 3

    The plan

    union every pair; for each root of size s: pairs += seen × s; seen += s
    

    Complexity

    Time
    O(n + p)
    Space
    O(n)

    Union-find over the pairs, then one pass over the roots.

    Edge cases

    • No pairs: n(n - 1)/2.
    • Everyone in one country: 0.
    • n = 1: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public long journeyToMoon(int n, int[][] astronaut) {
            int[] parent = new int[n], size = new int[n];
            for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
            for (int[] p : astronaut) {             // a pair is from the same country
                int a = find(parent, p[0]), b = find(parent, p[1]);
                if (a != b) { parent[a] = b; size[b] += size[a]; }
            }
            long pairs = 0, seen = 0;
            for (int i = 0; i < n; i++) {
                if (find(parent, i) != i) continue;
                pairs += seen * size[i];            // pair each new country with everyone counted so far
                seen += size[i];
            }
            return pairs;
        }
    
        private int find(int[] parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    }

    C++

    class Solution {
    public:
        long long journeyToMoon(int n, vector<vector<int>>& astronaut) {
            vector<int> parent(n), size(n, 1);
            for (int i = 0; i < n; i++) parent[i] = i;
            for (const vector<int>& p : astronaut) {   // a pair is from the same country
                int a = find(parent, p[0]), b = find(parent, p[1]);
                if (a != b) { parent[a] = b; size[b] += size[a]; }
            }
            long long pairs = 0, seen = 0;
            for (int i = 0; i < n; i++) {
                if (find(parent, i) != i) continue;
                pairs += seen * size[i];            // pair each new country with everyone counted so far
                seen += size[i];
            }
            return pairs;
        }
    
        int find(vector<int>& parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    };

    Python

    class Solution:
        def journeyToMoon(self, n: int, astronaut: list[list[int]]) -> int:
            parent, size = list(range(n)), [1] * n
    
            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x
    
            for a, b in astronaut:                  # a pair is from the same country
                ra, rb = find(a), find(b)
                if ra != rb:
                    parent[ra] = rb
                    size[rb] += size[ra]
            pairs = seen = 0
            for i in range(n):
                if find(i) == i:
                    pairs += seen * size[i]         # pair each new country with everyone counted so far
                    seen += size[i]
            return pairs

    Common mistakes

    • Overflowing 32 bits for large n.
    • Forgetting astronauts that appear in no pair.

    Similar problems