Merge Two Score Lists

Merge Two Score Lists

Easy Programming Interview Data Structures 19 views
Explanation Complexity

Problem Statement

We have {x}. Make final score for each key as sum of scores from both lists (missing is 0). Output keys sorted with their final score.

Input Format

Line1: n. Next n lines: key score. Then line: m. Next m lines: key score.

Output Format

Lines: key totalScore.

Example

2
a 5
b 2
3
b 3
c 10
a -2
a 3
b 5
c 10

Constraints

n+m

Input / Output Format

Input Format
Line1: n. Next n lines: key score. Then line: m. Next m lines: key score.
Output Format
Lines: key totalScore.
Constraints
n+m

Examples

Input:
2 a 5 b 2 3 b 3 c 10 a -2
Output:
a 3 b 5 c 10

Example Solution (Public)

Programming Interview
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
i=0
n=int(lines[i].strip()); i+=1
mp={}
for _ in range(n):
  parts=(lines[i] if i<len(lines) else '').split(); i+=1
  if len(parts)<2: continue
  mp[parts[0]]=mp.get(parts[0],0)+int(parts[1])
m=int(lines[i].strip()) if i<len(lines) and lines[i].strip() else 0
i+=1
for _ in range(m):
  parts=(lines[i] if i<len(lines) else '').split(); i+=1
  if len(parts)<2: continue
  mp[parts[0]]=mp.get(parts[0],0)+int(parts[1])
out=[]
for k in sorted(mp.keys()):
  out.append(f'{k} {mp[k]}')
sys.stdout.write('\
'.join(out))

Official Solution Code

import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
i=0
n=int(lines[i].strip()); i+=1
mp={}
for _ in range(n):
  parts=(lines[i] if i<len(lines) else '').split(); i+=1
  if len(parts)<2: continue
  mp[parts[0]]=mp.get(parts[0],0)+int(parts[1])
m=int(lines[i].strip()) if i<len(lines) and lines[i].strip() else 0
i+=1
for _ in range(m):
  parts=(lines[i] if i<len(lines) else '').split(); i+=1
  if len(parts)<2: continue
  mp[parts[0]]=mp.get(parts[0],0)+int(parts[1])
out=[]
for k in sorted(mp.keys()):
  out.append(f'{k} {mp[k]}')
sys.stdout.write('\
'.join(out))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.