First Repeat Prefix Sum
Programming Interview
Hard
4 views
Problem Description
We have {x}. If never repeats, output -1.
Input Format
First line n. Second line n integers.
Output Format
One integer index or -1.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0])
a=list(map(int,p[1:1+n]))
seen=set([0])
sm=0
ans=-1
for i,x in enumerate(a, start=1):
sm+=x
if sm in seen:
ans=i
break
seen.add(sm)
sys.stdout.write(str(ans))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!