Swap Values of Two Keys
Programming Interview
Easy
5 views
Problem Description
You're given {x}. Then two keys k1 and k2 are provided. If both keys exist, swap their values. Finally output value of k1 and value of k2 (use NA if a key does not exist).
Input Format
First line n. Next n lines: key value. Last line: k1 k2.
Output Format
One line: val1 val2.
Sample Test Case
Input:
4
a red
b blue
c green
d black
a c
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
mp={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
mp[parts[0]]=parts[1]
q=(lines[1+n] if 1+n<len(lines) else '').split()
if len(q)>=2:
k1,k2=q[0],q[1]
if k1 in mp and k2 in mp:
mp[k1],mp[k2]=mp[k2],mp[k1]
v1=mp.get(k1,'NA')
v2=mp.get(k2,'NA')
sys.stdout.write(f'{v1} {v2}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!