Cheapest Bus Route - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional list of integers connections. 

Each element contains [f, t, id] meaning that bus id has a route from location f to location t. 

It costs one unit of money to get on a new bus, but if you stay on the same bus continuously, you only pay one unit. 

Return the minimum cost necessary to take the bus from location 0 to the largest location. Return -1 if it's not possible.

Constraints

n ≤ 1,000 where n is the number of bus stops

m ≤ 1,000 where m is the number of bus ids

c ≤ 100,000 where c is the length of connections

Example 1
Input

connections = [

    [0, 1, 0],
    [1, 2, 0],


    [0, 3, 1],

    [2, 4, 1],

    [3, 0, 1]

]
Output

2


Explanation

We can get on bus 0 at location 0 and get out at location 2. Then we get on bus 1 to location 4.



Example 2

Input

connections = [

    [0, 1, 0],

    [1, 2, 1],

    [2, 3, 0]

]

Output

3

Explanation

Even though we were on bus 0 originally, when we get on it again, we still pay a cost of one. This is 
because the bus wasn't taken continuously.



Solution :



title-img




                        Solution in C++ :

map<int, map<int, vector<int>>>
    edges;           // edges[i][j] gives all locations k, for stop i and bus id j
int mindp[1005];     // mindp[i] = min cost from stop i
int dp[1005][1005];  // dp[i][j] = cost of being at station i with
bool minused[1005];  // have we tried transferring out of station i yet?
int solve(vector<vector<int>>& connections) {
    int n = 0;
    edges.clear();
    int m = 0;
    for (auto& e : connections) {
        n = max(n, e[0] + 1);
        n = max(n, e[1] + 1);
        m = max(m, e[1] + 1);
        edges[e[0]][e[2]].push_back(e[1]);
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            dp[i][j] = 1e9;
        }
    }
    for (int i = 0; i < n; i++) minused[i] = false;
    mindp[0] = 0;
    for (int i = 1; i < n; i++) mindp[i] = 1e9;
    deque<pair<int, int>> q;
    for (int i = 0; i < m; i++) {
        dp[0][i] = 1;
        q.emplace_back(0, i);
    }
    while (q.size()) {
        int curr = q.front().first;
        int currbus = q.front().second;
        q.pop_front();
        // stay on the same bus
        for (int loc : edges[curr][currbus]) {
            int cost = min(mindp[curr] + 1, dp[curr][currbus]);
            if (cost < dp[loc][currbus]) {
                dp[loc][currbus] = cost;
                q.emplace_front(loc, currbus);
            }
            mindp[loc] = min(mindp[loc], dp[loc][currbus]);
        }
        if (!minused[curr]) {
            // try all routes out
            for (auto e : edges[curr]) {
                int busid = e.first;
                for (int loc : e.second) {
                    int cost = min(mindp[curr] + 1, dp[curr][busid]);
                    if (cost < dp[loc][busid]) {
                        dp[loc][busid] = cost;
                        q.emplace_back(loc, busid);
                    }
                    mindp[loc] = min(mindp[loc], dp[loc][busid]);
                }
            }
            minused[curr] = true;
        }
    }
    if (mindp[n - 1] == 1e9) return -1;
    return mindp[n - 1];
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[][] connections) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return Integer.compare(a[1], b[1]);
            }
        });
        // first element is the node, second element is shortest distance from 0 to that node
        // last element(or third element) is BUS ID
        Map<Integer, Set<State>> graph = new HashMap();
        int maxy = -1;
        int max_id = -1;
        for (int[] con : connections) {
            graph.putIfAbsent(con[0], new HashSet());
            graph.get(con[0]).add(new State(con[1], con[2]));

            maxy = Math.max(maxy, Math.max(con[0], con[1]));
            max_id = Math.max(max_id, con[2]);
        }
        // System.out.println("graph is " + graph.toString());
        int[][] ref = new int[maxy + 1][max_id + 1];
        for (int[] x : ref) Arrays.fill(x, Integer.MAX_VALUE);
        for (int j = 0; j < ref[0].length; j++) {
            ref[0][j] = 0;
        }
        boolean[][] vis = new boolean[maxy + 1][max_id + 1];

        if (!graph.containsKey(0)) {
            return -1;
        }
        for (State start : graph.get(0)) {
            pq.offer(new int[] {0, 0, start.bus});
        }
        while (!pq.isEmpty()) {
            int[] promising = pq.poll();
            int node = promising[0];
            int weight = promising[1];
            int curr_bus = promising[2];
            if (vis[node][curr_bus] || ref[node][curr_bus] < weight)
                continue;
            vis[node][curr_bus] = true;
            if (!graph.containsKey(node))
                continue;
            for (State neighbor : graph.get(node)) {
                int new_dist = weight;
                if (neighbor.bus != curr_bus) {
                    new_dist++;
                }
                int new_node = neighbor.neighbor;
                if (ref[new_node][neighbor.bus] > new_dist) {
                    pq.offer(new int[] {new_node, new_dist, neighbor.bus});
                    ref[new_node][neighbor.bus] = new_dist;
                }
            }
        }
        // System.out.println(Arrays.deepToString(ref));
        int ret = Integer.MAX_VALUE;
        for (int x : ref[maxy]) {
            ret = Math.min(ret, x);
        }
        if (ret == Integer.MAX_VALUE)
            return -1;
        return ret + 1;
    }
}
class State {
    int neighbor;
    int bus;
    public State(int neighbor, int bus) {
        this.neighbor = neighbor;
        this.bus = bus;
    }
    @Override
    public String toString() {
        return neighbor + " " + bus;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, routes):
        s = 0
        target_end = float("-inf")

        for route in routes:
            target_end = max(target_end, route[0])
            target_end = max(target_end, route[1])

        if s == target_end:
            return 0

        graph = collections.defaultdict(list)

        for start, end, id in routes:
            graph[start].append((id, end))

        pq = []

        for id, end in graph[s]:
            heapq.heappush(pq, (1, id, end))

        visited = set()

        while pq:
            cost, id, e = heapq.heappop(pq)
            visited.add((id, e))

            if e == target_end:
                return cost

            for connected_id, end in graph[e]:
                if (connected_id, end) in visited:
                    continue

                if id == connected_id:
                    heapq.heappush(pq, (cost, connected_id, end))
                else:
                    heapq.heappush(pq, (cost + 1, connected_id, end))

        return -1
                    


View More Similar Problems

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 →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →