Task 1: No Connection
You are given a list of routes, @routes.
Write a script to find the destination with no further outgoing connection.
Example 1: Input: (["B","C"], ["D","B"], ["C","A"]) → Output: "A"
Example 2: Input: (["A","Z"]) → Output: "Z"
Method Explanation
Each route [source, destination] represents a directed edge in a graph. A city with no outgoing connection is a vertex with out-degree $0$ that appears as a destination in at least one route, but never appears as a source.
We can solve this in $O(N)$ time and space using two sets (or hashes):
- Collect all cities that appear first in a route into a
sourcesset. - Collect all cities that appear second in a route into a
destinationsset. - Compute the set difference $\text{destinations} \setminus \text{sources}$ and return the terminal city (or
undef/Noneif the graph forms a cycle).
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Str);
signature_for find_destination => (
method => 0,
positional => [ ArrayRef [ ArrayRef [Str] ] ],
);
sub find_destination ($routes_ref) {
my %sources;
my %destinations;
for my $route (@$routes_ref) {
my ( $source, $destination ) = @$route;
$sources{$source} = 1;
$destinations{$destination} = 1;
}
for my $city ( sort keys %destinations ) {
if ( !exists $sources{$city} ) {
return $city;
}
}
return;
}
Python Solution
from collections.abc import Sequence
def find_destination(routes: Sequence[Sequence[str]]) -> str | None:
"""Find the destination with no further outgoing connection from routes."""
sources: set[str] = set()
destinations: set[str] = set()
for route in routes:
source, destination = route
sources.add(source)
destinations.add(destination)
no_outgoing = sorted(destinations - sources)
if no_outgoing:
return no_outgoing[0]
return None