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

0% completed

Vote For New Content
Over-engineered solution: a simple counter is all you need

Davide Pugliese

Feb 28, 2024

I am looking into problems to learn Dynamic Programming. I think this was not a good example of a problem that needs such a thing. In my view, the proposed solution is over engineered as you literally need only a counter. If you want to improve this solution you can pass as a parameter to the trie the string and the two pointers (left, right) so you don't create a new string each time.

import java.util.Map; import java.util.HashMap; class TrieNode { Map<Character, TrieNode> children = new HashMap<>(); // Representing each character of the alphabet. boolean isEnd = false; // To determine if the current TrieNode marks the end of a word. } class Trie { TrieNode root; Trie() { root = new TrieNode(); } void insert(String word) { var node = root; for (char ch: word.toCharArray()) { node = node.children.computeIfAbsent(ch, c -> new TrieNode()); } node.isEnd = true; } boolean searchPrefix(String needle) { var node = root; for (char ch : needle.toCharArray()) { if (!node.children.containsKey(ch)) { return false; } node = node.children.get(ch); } return true; } boolean search(String needle) { var node = root; for (char ch : needle.toCharArray()) { if (!node.children.containsKey(ch)) { return false; } node = node.children.get(ch); } return node.isEnd; } } class Solution { // Method to calculate minimum extra characters. public int minExtraChar(String str, String[] dictionary) { // ToDo: Write Your Code Here. var trie = new Trie(); for (var s : dictionary) { trie.insert(s); } int counter = 0; StringBuilder tmp = new StringBuilder(); for (int right = 0, left = 0; right < str.length(); ) { tmp.append(str.charAt(right)); var s = tmp.toString(); if (trie.search(s)) { tmp.setLength(0); right++; } else if (!trie.searchPrefix(s)) { left++; right++; counter++; tmp.setLength(0); } else { right++; } } return counter; } }

1

0

Comments
Comments
D
Davide Pugliese2 years ago

You might as well return a Pair instead of a boolean so that in one go you have both the answers, whether it is a prefix and an endWord. This way you call just one method instead of 2.

On this page