A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:
The students must be in the order of non-decreasing height. Two boys or two girls must not be adjacent to each other. You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not. This one is mine but I am getting the wrong answer in 3 testcases. here, a is the array of boys height and b is the array of girls.
a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""
while i<n and j<n:
if a[i]<b[j]:
x+="b"
i+=1
elif a[i]==b[j]:
if len(x)==0:
x+="b"
i+=1
elif x[-1]=="b":
x+="g"
j+=1
else:
x+="b"
i+=1
else:
x+="g"
j+=1
while i<n:
x+="b"
i+=1
while j<n:
x+="g"
j+=1
p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
return "NO"
else:
return "YES"
I saw your code. So the mistake is in the part where you check for 2 boys and 2 girls.
The condition that you wrote is:
p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
Note that '?=' is lookahead before which means it will only give true if you have 2 girls before 2 boys or 2 boys before 2 girls. This logic will fail when the case is such that the string comes out to be -> GBBG or BGGB or GBBGBG or BGGBGB
I would suggest using a flag system instead because you just need to keep track of the last entry in the line. Let flag be '0' for boy and '1' for girl
flag=2
success = "Yes";
while i<n and j<n:
if(a[i]<b[j]):
if(flag==2):
flag = 0
elif(flag == 0):
success="No"
break;
else:
flag=0
elif(a[i]==b[j])
if(flag==2):
flag=0
elif(flag==0):
flag=1
else:
flag=0
else:
if(flag==2):
flag=1
elif(flag==1):
success="No"
break;
else:
flag=1
print(success)