Code Logo

Campus Shuttle Loop Coverage

Published atDate not available
Medium 0 views
Like0

This problem feels like a little puzzle you can solve one step at a time. In Campus Shuttle Loop Coverage, you are trying to work toward the right number by following one clear idea.

Here, you are mostly deciding whether a rule stays true while you look through the input. Sometimes that means checking if things are connected, balanced, or allowed. Sometimes it means noticing the first place where the rule breaks. The answer depends on being careful from beginning to end.

For example, if the input is n = 6, walkways = [[0,1],[1,2],[2,3],[3,4],[4,5]], start = 0, the answer is 6. The shuttle stops in every building along the loop without revisiting any stops. Another example is n = 4, walkways = [[0,1],[2,3]], start = 1, which gives 2. The loop covers buildings 1 and 0, while the other set stays untouched.

This problem needs a little more patience than a very easy one. The key is noticing the exact moment when the rule stays true or breaks.

Example Input & Output

Example 1
Input
n = 6, walkways = [[0,1],[1,2],[2,3],[3,4],[4,5]], start = 0
Output
6
Explanation

The shuttle stops in every building along the loop without revisiting any stops.

Example 2
Input
n = 4, walkways = [[0,1],[2,3]], start = 1
Output
2
Explanation

The loop covers buildings 1 and 0, while the other set stays untouched.

Example 3
Input
n = 5, walkways = [[0,1],[1,2],[2,0],[3,4]], start = 2
Output
3
Explanation

Buildings 0, 1, and 2 are visited; the remaining pair sits in another component.

Algorithm Flow

Recommendation Algorithm Flow for Campus Shuttle Loop Coverage
Recommendation Algorithm Flow for Campus Shuttle Loop Coverage

Best Answers

java
import java.util.*;

class Solution {
    public int shuttle_loop_coverage(int n, int[][] walkways, int start) {
        if (n == 0) return 0;
        List<Integer>[] adj = new List[n];
        for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
        for (int[] path : walkways) {
            int u = path[0], v = path[1];
            if (u < n && v < n) {
                adj[u].add(v);
                adj[v].add(u);
            }
        }
        Set<Integer> visited = new HashSet<>();
        visited.add(start);
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            for (int neighbor : adj[curr]) {
                if (!visited.contains(neighbor)) {
                    visited.add(neighbor);
                    queue.add(neighbor);
                }
            }
        }
        return visited.size();
    }
}