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

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 →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →