Fix Flight Itinerary - Google Top Interview Questions
Problem Statement :
You are given a list of uppercase alphabet strings itinerary and a two-dimensional list of uppercase alphabet strings edges. itinerary contains the list of airports you visited in order but the airport names may be misspelled. Each element in edges contains [source, dest] meaning there is a flight that goes from source to dest. Every airport has the same length of 3. Return the minimum number of characters you can change in itinerary such that the itinerary becomes valid. You can assume that there is a solution. Constraints n * m ≤ 200,000 where n is the length of itinerary, m is the length of edges Example 1 Input itinerary = ["YYZ", "SFO", "JFK"] edges = [ ["YYZ", "SEA"], ["SEA", "JAM"], ["SEA", "JFL"] ] Output 3 Explanation We change "SFO" to "SEA" for 2 character changes and "JFK" to 'JFL" for 1 character change. In total, we made 3 character changes. Example 2 Input itinerary = ["YYZ", "SFO", "JFK"] edges = [ ["YYZ", "SFO"], ["SFO", "JFK"] ] Output 0 Explanation We can go directly from "YYZ" to "SFO" to "JFK". So no characters need to be changed.
Solution :
Solution in C++ :
int solve(vector<string>& arr, vector<vector<string>>& edge) {
int n = arr.size();
int m = edge.size();
set<string> st;
for (auto it : edge) {
st.insert(it[0]);
st.insert(it[1]);
}
map<string, int> mp;
vector<string> str;
int cnt = 0;
for (string s : st) {
str.push_back(s);
mp[s] = cnt;
cnt += 1;
}
int sz = str.size();
vector<vector<int>> adj(sz);
for (auto it : edge) {
int u = mp[it[0]], v = mp[it[1]];
adj[u].push_back(v);
}
queue<array<int, 2>> q;
for (int i = 0; i < sz; i++) {
cnt = 0;
for (int j = 0; j < 3; j++) {
if (str[i][j] != arr[0][j]) cnt += 1;
}
q.push({cnt, i});
}
cnt = 0;
int ans = INT_MAX;
vector<int> dis(sz, INT_MAX);
while (cnt < n) {
cnt += 1;
set<int> id;
while (q.size()) {
array<int, 2> tmp = q.front();
q.pop();
if (cnt == n) {
ans = min(ans, tmp[0]);
continue;
}
for (int a : adj[tmp[1]]) {
int chk = 0;
for (int i = 0; i < 3; i++) {
if (arr[cnt][i] != str[a][i]) {
chk += 1;
}
}
dis[a] = min(dis[a], tmp[0] + chk);
id.insert(a);
}
}
for (int x : id) {
q.push({dis[x], x});
dis[x] = INT_MAX;
}
}
return ans;
}
Solution in Java :
import java.util.*;
class Solution {
private Map<String, Integer> portMap = new LinkedHashMap();
private Map<String, List<String>> graph = new HashMap();
private int index = 0;
private int infi = Integer.MAX_VALUE / 2;
private int ans = Integer.MAX_VALUE;
private Set<String> ports = new HashSet();
public int solve(String[] itinerary, String[][] edges) {
for (String[] edge : edges) {
String u = edge[0];
String v = edge[1];
// incoming edges
graph.computeIfAbsent(v, k -> new ArrayList()).add(u);
if (!portMap.containsKey(u)) {
portMap.put(u, index++);
}
if (!portMap.containsKey(v)) {
portMap.put(v, index++);
}
ports.add(u);
ports.add(v);
}
List<String> portList = new ArrayList(ports);
int[][] dp = new int[portList.size()][itinerary.length];
for (int i = 0; i < portList.size(); i++) {
String port = portList.get(i);
dp[portMap.get(port)][0] = getDiff(port, itinerary[0]);
}
for (int idx = 1; idx < itinerary.length; idx++) {
for (int j = 0; j < portList.size(); j++) {
String port = portList.get(j);
int diff = getDiff(port, itinerary[idx]);
if (graph.get(port) == null) {
dp[portMap.get(port)][idx] = infi;
} else {
int min = Integer.MAX_VALUE;
for (String prevPort : graph.get(port)) {
min = Math.min(min, dp[portMap.get(prevPort)][idx - 1] + diff);
}
dp[portMap.get(port)][idx] = min;
}
}
}
for (int i = 0; i < portList.size(); i++) {
ans = Math.min(ans, dp[portMap.get(portList.get(i))][itinerary.length - 1]);
}
return ans;
}
private int getDiff(String str1, String str2) {
int count = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i))
++count;
}
return count;
}
}
Solution in Python :
class Solution:
def solve(self, itinerary, edges):
n = len(itinerary)
def diff(a, b):
"""The cost to change the airport name `a` to `b` is the number of different characters."""
return sum(x != y for x, y in zip(a, b))
# We will use dynamic programming.
# dp[port] is the minimum cost to reach airport `port`.
# We can freely change the first airport in the itinerary,
# incurring only the cost of the name change itself.
dp = dict()
airports = set(e[0] for e in edges)
for p in airports:
dp[p] = diff(itinerary[0], p)
for i in range(1, n):
nextdp = dict()
for p1, p2 in edges:
# If it's possible to reach p1 at the previous index...
if p1 in dp:
# then it's now possible to reach p2 at the current index.
# We incur an additional cost to change `itinerary[i]` to `p2`.
cost = dp[p1] + diff(itinerary[i], p2)
if p2 not in nextdp or cost < nextdp[p2]:
nextdp[p2] = cost
dp = nextdp
# Choose the lowest cost among all possible final airports.
return min(dp.values())
View More Similar Problems
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 →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →