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

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →