First Index Map

First Index Map

Medium Python Dictionaries 12 views
Explanation Complexity

Problem Statement

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.

Example

5
10 20 10 30 20
4
10
20
30
40
1
2
4
-1

Constraints

n,q

Input / Output Format

Input Format
Line1: n. Line2: n integers. Line3: q. Next q lines: value.
Output Format
q lines indices.
Constraints
n,q

Examples

Input:
5 10 20 10 30 20 4 10 20 30 40
Output:
1 2 4 -1

Example Solution (Public)

Python
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))

Official Solution Code

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

                                        
Please login to submit solutions.