Dictionary Nomad - Amazon Top Interview Questions


Problem Statement :


You are given a list of strings dictionary and two strings start and end. You want to reach from start to end by modifying one character at a time and making sure each resulting word is also in the dictionary. Words are case-sensitive.

Return the minimum number of steps it would take to reach end. Return -1 if it's not possible.

Constraints

0 ≤ n * m ≤ 300,000 where n is the length of dictionary and m is the length of the longest string

Example 1

Input

dictionary = ["day", "say", "soy"]

start = "soy"

end = "day"

Output

3

Explanation

We can take this path: ["soy", "say", "day"].

Example 2

Input

dictionary = ["day", "soy"]

start = "soy"

end = "day"

Output

-1

Explanation

There's no way to change 1 character to reach "day".



Solution :



title-img




                        Solution in C++ :

int solve(vector<string>& dictionary, string start, string end) {
    unordered_set<string> seen{start}, dict(dictionary.begin(), dictionary.end());
    queue<string> q{{start}};
    int steps = 0;
    while (!q.empty()) {
        int sz = q.size();
        steps++;
        while (sz-- > 0) {
            auto& p = q.front();
            if (p == end) return steps;
            q.pop();
            for (int i = 0; i < p.size(); i++) {
                char old = p[i];
                for (char c = 'a'; c <= 'z'; c++) {
                    p[i] = c;
                    if (dict.count(p) && !seen.count(p)) {
                        seen.insert(p);
                        q.push(p);
                    }
                }
                p[i] = old;
            }
        }
    }
    return -1;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(String[] dictionary, String start, String end) {
        Set<String> dict = new HashSet<>();
        for (String d : dictionary) dict.add(d);
        Set<String> visited = new HashSet<>();
        Deque<String> q = new ArrayDeque<>();
        q.add(start);
        int steps = 0;
        while (!q.isEmpty()) {
            steps++;
            int sz = q.size();
            for (int i = 0; i < sz; i++) {
                String cur = q.remove();
                if (visited.contains(cur))
                    continue;
                visited.add(cur);
                if (cur.equals(end))
                    return steps;
                // try to generate all possible strings for next level
                for (int j = 0; j < cur.length(); j++) {
                    // for each possition, we try [a-z] chars
                    for (char c = 'a'; c <= 'z'; c++) {
                        String newstr =
                            cur.substring(0, j) + c + cur.substring(j + 1, cur.length());
                        if (dict.contains(newstr))
                            q.offer(newstr);
                    }
                }
            }
        }
        return -1;
    }
}

/*
build a bi directional graph, node u and v will have an edge if u and v have only
one character difference

add start and end too in graph

find shorted path to reach from start to end using bfs then

challenge: how to build graph efficiently?

*/
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, dictionary, start, end):
        words, visited = set(dictionary), set()
        q = deque()
        q.append(start)

        level = 1
        while len(q) > 0:
            size = len(q)
            for i in range(size):
                cur = q.popleft()
                if cur == end:
                    return level
                for idx in range(len(cur)):
                    for c in range(97, 97 + 26):
                        new_word = cur[:idx] + chr(c) + cur[idx + 1 :]
                        if new_word not in visited and new_word in words:
                            q.append(new_word)
                            visited.add(new_word)
            level += 1
        return -1
                    


View More Similar Problems

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 →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →