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

Array-DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3

View Solution →

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →