We need to print the longest sequence of nos.
Input = [2,3,4,5,8,0]
Output= 3,[2,3,4,5]
Input=[2,3,4,5,8,0,10,9,8,7,6,5]
Output= 5,[10,9,8,9,6,5]
Below is the code that I have written, can someone please help me with optimising the code
I have used 2 flags, flag1 refers to the forward seq, and flag2 for the reverse seq, kepping in mind the below mentioned test case
In = [2,3,4,3,2,1]
Out = 3, [4,3,2,1]
I got this question in one of the interview, and I took a lot of time to solve this almost 50% of my interview time, any tips on attempting such questions at a faster pace if faced during an interview.
Here is my solution, please help me optimize it.
l=[2,3,4,3,2,1]
flag1=0
flag2=0
index=0
seq=0
seq_dict={}
n=len(l)
for i in range(n-1):
if (l[i]+1==l[i+1]):
if (flag2==1):
index=i
seq_dict.update({seq:[index,flag1,flag2]})
seq=0
flag2=0
elif(flag1==0 and i==n-2):
index=i+1
flag1=1
seq+=1
seq_dict.update({seq:[index,flag1,flag2]})
flag1=1
seq+=1
elif (l[i]-1==l[i+1]):
if (flag1==1):
index=i-1
seq_dict.update({seq:[index,flag1,flag2]})
seq=0
flag1=0
elif(flag2==1 and i==n-2):
index=i+1
flag2=1
seq+=1
seq_dict.update({seq:[index,flag1,flag2]})
flag2=1
seq+=1
else:
if(seq!=0 and (flag1==1 or flag2==1)):
index=i
seq_dict.update({seq:[index,flag1,flag2]})
seq=0
flag1=0
flag2=0
index=0
final=[]
m=max(seq_dict)
print(m)
end=seq_dict[m][0]
while(m>=0):
final.append(l[end-m])
m-=1
print(final)
rj_47 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.