First Pair with Sum K
Python
Hard
2 views
Problem Description
Read n integers and target K, find the first pair in reading order that sums to K. Output their 1-based indices i j (i
Input Format
First line n K. Second line n integers.
Output Format
Two indices or -1.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0]); K=int(p[1])
a=list(map(int,p[2:2+n]))
first_pos={}
ans=None
for j,val in enumerate(a, start=1):
need=K-val
if need in first_pos:
ans=(first_pos[need],j)
break
if val not in first_pos:
first_pos[val]=j
if ans is None:
sys.stdout.write('-1')
else:
sys.stdout.write(f'{ans[0]} {ans[1]}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!