Counter with Delete

Counter with Delete

Medium Python Dictionaries 14 views
Explanation Complexity

Problem Statement

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.

Constraints

1

Input / Output Format

Input Format
First line q. Next q lines commands.
Output Format
One integer keysLeft.
Constraints
1

Examples

Input:
6 INC a INC a INC b DEC a DEC a DEC b
Output:
0

Example Solution (Public)

Python
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)))

Official Solution Code

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)))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.