Count Pairs with Same Value
Python
Medium
4 views
Problem Description
Read n keys with integer values. Count how many unordered pairs of keys have same value. Output the number.
Input Format
First line n. Next n lines: key value.
Output Format
One integer pairCount.
Sample Test Case
Input:
5
a 1
b 1
c 2
d 2
e 2
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
valCount={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
v=int(parts[1])
valCount[v]=valCount.get(v,0)+1
ans=0
for c in valCount.values():
ans+=c*(c-1)//2
sys.stdout.write(str(ans))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!