Border Crossing - Google Top Interview Questions


Problem Statement :


You are given two-dimensional lists of integers roads and countries as well as integers start and end. 
Each element in roads contains [x, y, weight] meaning that to travel from city x to y costs weight. Each 
element countries[i] represents all of the cities that belong to country i. Every city belongs to exactly 
one country.



You are currently in city start and want to travel to city end. During this trip, you want to minimize 
country-to-country border hops as a first priority, and then minimize total weight. Return a list of two 
elements where the first is the number of country-to-country hops and the second element is the total 
weight needed to make this trip. You can assume there is a solution.



Constraints



1 ≤ n ≤ 100,000 where n is the length of roads

Example 1

Input

roads = [

    [0, 1, 1],

    [1, 2, 1],

    [0, 2, 4]

]


countries = [

    [0],

    [1],

    [2]

]

start = 0

end = 2

Output

[1, 4]

Explanation

There are two paths from start to end, [0, 2] and [0, 1, 2]. [0, 2] crosses country boarder 1 time and has 
total weight of 4. Path [0, 1, 2] crosses country boarders 2 times and has total weight of 3. Thus we 
return [1, 4].



Example 2

Input

roads = [

    [0, 1, 1],

    [1, 3, 2],

    [0, 2, 2],

    [2, 3, 2]

]

countries = [

    [0],

    [1, 2],

    [3]

]

start = 0

end = 3

Output

[2, 3]

Explanation

There are two paths from start to end, [0, 1, 3] and [0, 2, 3]. Path [0, 1, 3] crosses country boarders 2 
times and has total weight of 3. Path [0, 2, 3] crosses country boarder 2 times and has total weight of 4. 
Thus we return [2, 3].



Solution :



title-img




                        Solution in C++ :

vector<int> solve(vector<vector<int>>& roads, vector<vector<int>>& countries, int start, int end) {
    int n = 0;
    for (auto& road : roads) {
        n = max(road[0], n);
        n = max(road[1], n);
    }
    n++;
    vector<vector<pair<int, int>>> graph(n);
    vector<int> country(n);
    for (int i = 0; i < (int)countries.size(); i++) {
        for (auto& who : countries[i]) {
            country[who] = i;
        }
    }
    for (auto& road : roads) {
        graph[road[0]].push_back({road[1], road[2]});
    }
    list<int> q;
    q.push_back(start);
    vector<pair<int, int>> cost(n);
    for (int i = 0; i < n; i++) {
        cost[i] = {INT_MAX, INT_MAX};
    }
    cost[start] = {0, 0};
    while (!q.empty()) {
        int curr = q.front();
        q.pop_front();
        for (auto& [v, w] : graph[curr]) {
            int change = country[v] != country[curr];
            if (cost[v].first > cost[curr].first + change) {
                cost[v].first = cost[curr].first + change;
                cost[v].second = cost[curr].second + w;
                if (change) {
                    q.push_back(v);
                } else {
                    q.push_front(v);
                }
            } else if (cost[v].first == cost[curr].first + change &&
                       cost[v].second > cost[curr].second + w) {
                cost[v].second = cost[curr].second + w;
                if (change) {
                    q.push_back(v);
                } else {
                    q.push_front(v);
                }
            }
        }
    }
    return {cost[end].first, cost[end].second};
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[] solve(int[][] roads, int[][] countries, int source, int end) {
        HashMap<Integer, List<int[]>> g = new HashMap<>();

        for (int[] road : roads) {
            int u = road[0];
            int v = road[1];
            if (!g.containsKey(u)) {
                g.put(u, new ArrayList<>());
            }
            g.get(u).add(new int[] {v, road[2]});
        }

        HashMap<Integer, Integer> country = new HashMap<>();
        for (int i = 0; i < countries.length; i++) {
            for (int j : countries[i]) {
                country.put(j, i);
            }
        }

        PriorityQueue<int[]> pq = new PriorityQueue<>((p, q) -> {
            return Long.compare(p[1] * (long) 1e12 + p[2], q[1] * (long) 1e12 + q[2]);
        });

        pq.add(new int[] {source, 0, 0});

        HashSet<Integer> relaxed = new HashSet<>();

        while (pq.size() > 0) {
            int[] node = pq.poll();

            if (node[0] == end) {
                return new int[] {node[1], node[2]};
            }

            int u = node[0];

            if (relaxed.contains(u))
                continue;

            relaxed.add(u);

            if (g.containsKey(u)) {
                for (int[] edge : g.get(u)) {
                    int v = edge[0];
                    pq.add(new int[] {v, node[1] + (country.get(u) != country.get(v) ? 1 : 0),
                        node[2] + edge[1]});
                }
            }
        }

        return new int[] {0, 0};
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, roads, countries, start, end):
        cntry = defaultdict(int)
        for i, arr in enumerate(countries):
            for c in arr:
                cntry[c] = i

        adj = defaultdict(list)
        for x, y, w in roads:
            if cntry[x] != cntry[y]:
                w += 10 ** 10
            adj[x].append((y, w))

        dist = defaultdict(lambda: 10 ** 20)
        dist[start] = 0
        visited = set()

        h = [(0, start)]
        while h:
            d, city = heappop(h)
            if city in visited:
                continue
            visited.add(city)
            for c, w in adj[city]:
                if dist[c] > d + w:
                    dist[c] = d + w
                    heappush(h, (d + w, c))

        return dist[end] // 10 ** 10, dist[end] % 10 ** 10
                    


View More Similar Problems

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →