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

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →