Trie Prefix Counter (OOP)
Programming Interview
Hard
8 views
Problem Description
You're given {x}. Create Trie class. For COUNT output how many added words have this prefix.
Input Format
First line q. Next q lines operations.
Output Format
Outputs for COUNT.
Sample Test Case
Input:
7
ADD apple
ADD app
COUNT ap
COUNT app
ADD apply
COUNT app
COUNT b
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
class Node:
__slots__=('nxt','cnt')
def __init__(self):
self.nxt={}
self.cnt=0
class Trie:
def __init__(self):
self.root=Node()
def add(self,w):
cur=self.root
for ch in w:
if ch not in cur.nxt:
cur.nxt[ch]=Node()
cur=cur.nxt[ch]
cur.cnt+=1
def count(self,prefix):
cur=self.root
for ch in prefix:
if ch not in cur.nxt:
return 0
cur=cur.nxt[ch]
return cur.cnt
tr=Trie()
out=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
if parts[0]=='ADD':
tr.add(parts[1])
else:
out.append(str(tr.count(parts[1])))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!