Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
With the given test cases, there's an O(n) solution that passes

Lee

Feb 22, 2024

I think this could fail under certain test cases, however.

class Solution: def minExtraChar(self, s, dictionary): # build the Trie root = TrieNode() for word in dictionary: node = root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.isEnd = True # iterate over string counting unused characters totalUnused = 0 curUnused = 0 node = root for ch in s: curUnused += 1 if ch not in node.children: totalUnused += curUnused curUnused = 0 node = root continue node = node.children[ch] if node.isEnd: curUnused = 0 node = root totalUnused += curUnused return totalUnused

1

0

Comments
Comments

On this page