First Non-Repeating Character Index
Python
Medium
5 views
Problem Description
For each testcase you get string s. Output index (0-based) of first character that appears exactly once. If none, output -1.
Input Format
First line t. Next t lines strings.
Output Format
t lines indices.
Sample Test Case
Input:
3
aabbc
leetcode
zz
Official Solution
import sys
from collections import Counter
lines=sys.stdin.read().splitlines()
if not lines:
sys.exit(0)
try:
t=int(lines[0].strip())
except Exception:
t=0
idx=1
out=[]
for _ in range(t):
s=lines[idx] if idx<len(lines) else ''
idx+=1
cnt=Counter(s)
ans=-1
for i,ch in enumerate(s):
if cnt[ch]==1:
ans=i
break
out.append(str(ans))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!