First Index Map
Python
Medium
2 views
Problem Description
Read n integers. Store the first index (1-based) for each distinct value. Then q queries follow, each query is a value. Output its first index or -1.
Input Format
Line1: n. Line2: n integers. Line3: q. Next q lines: value.
Output Format
q lines indices.
Sample Test Case
Input:
5
10 20 10 30 20
4
10
20
30
40
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<3:
sys.exit(0)
n=int(lines[0].strip())
a=list(map(int,lines[1].split()[:n]))
mp={}
for i,v in enumerate(a, start=1):
if v not in mp:
mp[v]=i
q=int(lines[2].strip())
out=[]
for i in range(q):
v=int((lines[3+i] if 3+i<len(lines) else '0').strip())
out.append(str(mp.get(v,-1)))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!