Rename Key Safely
Python
Medium
2 views
Problem Description
Read q operations: SET k v, RENAME old new. RENAME works only if old exists and new does not exist. At end output number of keys and then keys sorted.
Input Format
First line q. Next q lines operations.
Output Format
First line count, next lines keys.
Sample Test Case
Input:
5
SET a 1
SET b 2
RENAME a c
RENAME b c
RENAME b d
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 not parts: continue
if parts[0]=='SET':
mp[parts[1]]=parts[2]
else:
old=parts[1]; new=parts[2]
if old in mp and new not in mp:
mp[new]=mp[old]
del mp[old]
out=[str(len(mp))]
for k in sorted(mp.keys()):
out.append(k)
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!