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 :
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
Tree: Level Order Traversal
Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F
View Solution →Binary Search Tree : Insertion
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <
View Solution →Tree: Huffman Decoding
Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t
View Solution →Binary Search Tree : Lowest Common Ancestor
You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b
View Solution →Swap Nodes [Algo]
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from
View Solution →Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →