Minimum Distance Between 1's
The 2 approaches which I had for the problem are mentioned below, basically the second approach gives a TC of O(n^2) and the first one gives a TC of O(n). The first one passes all the Test Cases whereas the second one fails 1 for Limit Exceeded.
# cook your dish here
T=int(input())
while(T):
def get_dist(x1,y1):
if(abs(x1-y1)%2!=0):
return 1
else:
return 2
n=int(input())
st=input()
s_len=len(st)
m=float('inf')
p1,p2,first=0,0,False
for i in range(s_len):
if(st[i]=='1' and first==True):
p2=i
if(get_dist(p1,p2)<m):
m=get_dist(p1,p2)
if(m==1):
break
elif(st[i]=='1'):
p1=i
first=True
print(m)
T-=1
''' Second Approach '''
T=int(input("What's T? "))
while(T):
n=int(input("What's n? "))
st=input("What's st? ")
indices=[]
le=len(st)
for i in range(le):
if(st[i]=="1"):
indices.append(i)
le_ind=len(indices)
# Now I have all the instances of 1 in the indices list
chk=False
for i in range(le_ind-1):
for j in range(i+1,le_ind):
if(abs(indices[i]-indices[j])%2!=0):
print(1)
chk=True
break
if(chk==True):
break
if(chk==False):
print(2)
T-=1
Comments
Post a Comment