Flipkart Interview Question for SDE1s


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming the dictionary is an array of strings, then the best structure to test with would be a Trie. Using a Trie, the search would effectively operate a O(n*m) complexity where n is the number of words and m is the 'length' of the words to construct the Trie and O(n^2m) to research the word list for the longest compound word.

static class TrieNode<T>{
    HashMap<T,TrieNode<T>> children = new HashMap<T, TrieNode<T>>();
    boolean isTerminated;
}

static void addWordToTrie(String word, TrieNode<Character> head){
    TrieNode<Character> temp = head;
    int i = 0;
    while(i < word.length()){
        Character c = word.charAt(i);
        TrieNode<Character> tempChild = temp.children.get(c);
        if(tempChild == null){
            tempChild = new TrieNode<Character>();
            temp.children.put(c, tempChild);
        }
        temp = tempChild;
        i++;
    }
    temp.isTerminated = true;
}

public static String getLargestCompoundWord(String[] dict){
    if(dict == null){
        throw new NullPointerException("\"dict\" may not be null");
    }
    //build the Trie
    TrieNode<Character> head = new TrieNode<Character>();
    for(String str : dict){
        addWordToTrie(str, head);
    }
    
    //complete the search
    Worker worker = new Worker(dict, head);
    worker.work();
    return worker.results();
}

static class Worker{
    TrieNode<Character> head;
    String[] dict;
    String result;

    Worder(String[] dict, TrieNode<Character> head){
        this.dict = dict;
        this.head = head;
        this.result = "";
    }
    
    void work(){
        for(String word : this.dict){
            if(word.length : this.result.length()){
                if(compoundCount(word, 0, 0) > 1){
                    this.result = word;
                }
            }
        }
    }
    
    boolean compountCount(String str, int start, int countedWords){
        if(start >= end){
            return countedWords > 1;
        }
        TrieNode<Character> temp = head;
        while(start < str.length){
            Character c = str.charAt(start);
            start++;
            TrieNode<Character> tempChild = temp.children.get(c);
            if(tempChild == null){
                return false;
            }
            if(tempChild.isTerminated){
                if(compoundCount(str, start, countedWords+1){
                    return true;
                }
            }
        }
        return false;
    }
    
    String getResults(){
        return this.result;
    }

- zortlord May 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>


using namespace std;
const int AB_LEN = 26;

static const unordered_set<string> dictionary {"dog", "cat", "rat"};

struct Node {
	Node (): isLeaf(false),
			 children(AB_LEN, nullptr)
	{}
	bool isLeaf;
	vector<Node*> children;	
	~Node () {
		for (auto &n : children) {
			releaseMem(n);
		}
	}
	void releaseMem(Node *n) {
		if (n) {
			for (auto &i : n->children) {
				releaseMem(i);
			}
			delete(n);
		}		
	}
};

bool isInDict(string str)
{
	if (dictionary.find(str) != dictionary.end()) { return true; }
	return false;
}

void insertToTrie(Node *t, string s)
{
	for (auto &is : s) {
		int os = is - 'a';
		if (t->children[os] == nullptr) {
			t->children[os] = new Node();
		}
		t = t->children[os];
	}
	t->isLeaf = true;
}



void printTrie(Node *t, string word)
{
	if (t && t->isLeaf) {
		cout << word << endl;
	}
	for (int i=0; i < AB_LEN; ++i) {
		string s{ char(i +'a')};
		if (t->children[i]) {
			printTrie(t->children[i], word + s);
		}
	}
}

Node *getTrie(string w)
{
	Node *n = new Node();
	for (int i=0; i < w.size(); ++i) {
		string suff = string(w.begin() + i, w.end());
		cout << "test getTrie: " << suff << endl;
		insertToTrie(n, suff);
	}
	return n;
}
void getCurrComb (Node *t, string currW, int &cnt)
{
	if (isInDict(currW)) {
		cout << "in dict " << currW << endl;
		++cnt;
		if(t->isLeaf) { ++cnt; }
	}
	for (int i=0; i < AB_LEN; ++i) {
		if (t->children[i]) {
			string s {char(i+'a')};
			getCurrComb(t->children[i], currW + s, cnt);
		}
	}
}

string getMaxCombWord ( vector<string> &words, int &maxCnt)
{
//	int maxCnt = 0;
	string word;
	Node *t = nullptr;
	for (auto &w : words) {
		t = getTrie(w);
		int currCnt = 0;
		getCurrComb(t, "", currCnt);
		if (currCnt > maxCnt) {
			maxCnt = currCnt;
			word = w;
		}
	}
	return word;
}

int main()
{
	vector<string> words { "dogcat", "dog", "cat", "dogcatrat", "dogcatraatratdog"};
	//Node *n = getTrie (str);
	int maxCnt = 0;
	string res = getMaxCombWord(words, maxCnt);
	cout << "res: " << res << endl;
	cout << "max cnt: " << maxCnt << endl;
	return 0;
}

here is the link to the solution in my github:
https://github.com/kohn1001/Algorithms/blob/master/src/max_breaks_to_dict_words_2.cpp

- Natty.Kohn September 05, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More