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
Compare two linked lists
You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis
View Solution →Merge two sorted linked lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C
View Solution →Get Node Value
This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t
View Solution →Delete duplicate-value nodes from a sorted linked list
This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -
View Solution →Cycle Detection
A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer
View Solution →Find Merge Point of Two Lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share
View Solution →