Swap Values of Two Keys

Swap Values of Two Keys

Easy Programming Interview Data Structures 20 views
Explanation Complexity

Problem Statement

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.

Example

4
a red
b blue
c green
d black
a c
green red

Constraints

1

Input / Output Format

Input Format
First line n. Next n lines: key value. Last line: k1 k2.
Output Format
One line: val1 val2.
Constraints
1

Examples

Input:
4 a red b blue c green d black a c
Output:
green red

Example Solution (Public)

Programming Interview
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}')

Official Solution Code

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

                                        
Please login to submit solutions.