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 :



title-img




                        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

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 →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →