Blocks to Spell Word - Google Top Interview Questions


Problem Statement :


You are given a list of lowercase alphabet strings words and a string target. Assuming you can pick at most one character from each string in words, return whether you can spell out target in any order.

Constraints

n ≤ 12 where n is the length of target

m ≤ 12 where m is the length of words

Example 1
Input

words = ["how", "do", "i", "shot", "web"]

target = "wow"

Output

True

Explanation

We can pick "w" from "how", "o" from "do" and "w" from "web".


Example 2

Input

words = ["bi", "n", "a", "r", "y"]

target = "binary"

Output

False

Explanation

There's no way to pick both "b" and "i".



Solution :



title-img




                        Solution in C++ :

struct Graph {
    // number of verticies
    int V;
    // number of removed verticies
    int removed;
    // adjacency list
    list<int>* adjs;
    // rem[i] = true if node i was removed from graph
    bool* rem;

    Graph(int V) {
        this->V = V;
        removed = 0;
        adjs = new list<int>[V];
        rem = new bool[V];
    }

    void addEdge(int vFrom, int vTo) {
        adjs[vFrom].push_back(vTo);
    }

    // removes a directed edge
    void removeEdge(int vFrom, int vTo) {
        // iterate to find vTo in vFrom's adjacency list
        for (list<int>::iterator it2 = adjs[vFrom].begin(); it2 != adjs[vFrom].end(); ++it2) {
            // found vTo in vFrom's adjacency list
            if (*it2 == vTo) {
                adjs[vFrom].erase(it2);
                removed += (rem[vFrom] = adjs[vFrom].empty());  // true if vFrom now has degree 0
                break;
            }
        }
    }
    void print() {
        for (int i = 0; i < V; ++i) {
            cerr << '
' << i << "-> ";
            if (rem[i]) continue;
            for (const int& adj : adjs[i]) cerr << adj << ", ";
        }
        cerr << '
';
    }
};

bool solve(vector<string>& words, string target) {
    const int W = words.size(), T = target.size();
    if (words.size() < target.length()) return false;

    // bipartite graph
    Graph g(W + T);
    // the degree of the node with the smallest degree
    int min_degree = INT_MAX, n1;
    // iterate over all words and form edges
    for (int i = 0; i < W; ++i) {
        for (int t = 0; t < T; ++t) {
            if (words[i].find(target[t]) != -1) {
                g.addEdge(i, W + t);
                g.addEdge(W + t, i);
            }
        }
        if (0 < g.adjs[i].size() && g.adjs[i].size() < min_degree) {
            min_degree = g.adjs[i].size();
            n1 = i;
        }
    }

    // removing words that cannot contribute to the target
    // returning false if a target character could not be found
    for (int i = 0; i < g.V; ++i) {
        g.removed += (g.rem[i] = g.adjs[i].empty());
        // if a letter in the target could not find a match in words
        if (i > W && g.rem[i]) return false;
    }

    // cerr << "start conditions";
    // g.print();
    int pairs = 0;
    int itr = 0;
    // while not all edges have been removed
    while (g.removed != g.V) {
        // n1's first neighbor
        int n2 = *g.adjs[n1].begin();
        // mark nodes n1 and n2 as removed and remove edges from other nodes pointing to them
        g.rem[n1] = true;
        g.rem[n2] = true;
        g.removed += 2;
        // cerr << '
' << "match " << ++itr << ": (" << min(n1, n2) << ", " << max(n1,n2) << ')';
        // g.print();
        // disconnect all edges n->n1
        for (int n = 0; n < g.V; ++n)
            if (!g.rem[n]) g.removeEdge(n, n1);
        // disconnect all edges n->n2
        // and calculate new min_degree and n1
        min_degree = INT_MAX;
        for (int n = 0; n < g.V; ++n) {
            if (g.rem[n]) continue;
            g.removeEdge(n, n2);
            if (!g.rem[n] && 0 < g.adjs[n].size() && g.adjs[n].size() < min_degree) {
                min_degree = g.adjs[n].size();
                n1 = n;
            }
        }
        // indicate a new pair was made
        ++pairs;
    }
    return pairs == T;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public boolean solve(String[] words, String target) {
        int N = words.length;
        int M = target.length();
        boolean[][] dp = new boolean[1 << M][N + 1];
        dp[0][0] = true;
        for (int bit = 0; bit < (1 << M); bit++) {
            for (int i = 1; i <= N; i++) {
                dp[bit][i] = dp[bit][i - 1];
                for (int j = 0; j < M; j++) {
                    if ((bit & (1 << j)) > 0) {
                        String use = Character.toString(target.charAt(j));
                        if (words[i - 1].contains(use))
                            dp[bit][i] |= dp[bit - (1 << j)][i - 1];
                    }
                }
            }
        }
        return dp[(1 << M) - 1][N];
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, words, target):
        @cache
        def go(i, mask):
            if i == len(target):
                return True

            for j, x in enumerate(words):
                if (mask & (1 << j)) == 0 and target[i] in x:
                    if go(i + 1, mask | (1 << j)):
                        return True

            return False

        return go(0, 0)
                    


View More Similar Problems

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

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 →