# 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;     // mindp[i] = min cost from stop i
int dp;  // dp[i][j] = cost of being at station i with
bool minused;  // 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 + 1);
n = max(n, e + 1);
m = max(m, e + 1);
edges[e][e].push_back(e);
}
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;
for (int i = 1; i < n; i++) mindp[i] = 1e9;
deque<pair<int, int>> q;
for (int i = 0; i < m; i++) {
dp[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, b);
}
});
// 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, new HashSet());

maxy = Math.max(maxy, Math.max(con, con));
max_id = Math.max(max_id, con);
}
// 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.length; j++) {
ref[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;
int weight = promising;
int curr_bus = promising;
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)
target_end = max(target_end, route)

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)

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

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

## Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

## Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

## Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

## Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

## Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that