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

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →