Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
The solution should use DP with Trie instead of Greedy with Trie.

Kai

Nov 10, 2024

The current C++ suggested solution uses Greedy algorithm with Trie structure but that doesn't cover all cases.

For example, when the input string s is "ecolloycollotkvzqpdaumuqgs" and the dictionary is ["flbri","uaaz","numy","laper","ioqyt","tkvz","ndjb","gmg","gdpbo","x","collo","vuh","qhozp","iwk","paqgn","m","mhx","jgren","qqshd","qr","qpdau","oeeuq","c","qkot","uxqvx","lhgid","vchsk","drqx","keaua","yaru","mla","shz","lby","vdxlv","xyai","lxtgl","inz","brhi","iukt","f","lbjou","vb","sz","ilkra","izwk","muqgs","gom","je"], the current Greedy solution returns 14 instead of 2.

This is because, in Greedy approach, the mapping characters are "c" "c" "tkvz", "qpdau" and "m".

However, this is not the maximum mapping character case: "collo", "collo", "tkvz", "qpdau" "muqgs" which left only 2 unmapped characters ("e" and "y")

class TrieNode { public: TrieNode() : children(26, nullptr), isWord(false) {} vector<TrieNode*> children; bool isWord; }; class Solution { public: int minExtraChar(string s, vector<string>& dictionary) { int n = s.length(); vector<int> dp(n + 1, 0); TrieNode* root = buildTrie(dictionary); for(int start = n - 1; start >= 0; start--) { TrieNode* node = root; // base case: skip the current letter and check from the next letter dp[start] = dp[start + 1] + 1; // check all substrings that starts with the current letter for(int end = start; end < n; end++) { if (!node->children[s[end] - 'a']) { break; } node = node->children[s[end] - 'a']; if (node->isWord) { dp[start] = min(dp[start], dp[end + 1]); } } } return dp[0]; } private: // helper function to convert the given dictionary to trie form TrieNode* buildTrie(vector<string>& dictionary) { TrieNode* root = new TrieNode(); for(string& word : dictionary) { TrieNode* node = root; for(char& c : word) { if (!node->children[c - 'a']) { node->children[c - 'a'] = new TrieNode(); } node = node->children[c - 'a']; } node->isWord = true; } return root; } };

1

0

Comments
Comments

On this page