Counter with Delete
Python
Medium
3 views
Problem Description
You have q commands: INC key, DEC key. Start counts at 0. If after DEC the count becomes 0, remove the key from dictionary. At end output number of keys left.
Input Format
First line q. Next q lines commands.
Output Format
One integer keysLeft.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
mp={}
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
cmd=parts[0]; k=parts[1]
if cmd=='INC':
mp[k]=mp.get(k,0)+1
else:
if k in mp:
mp[k]-=1
if mp[k]<=0:
del mp[k]
sys.stdout.write(str(len(mp)))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!