Problem with empty string

In the following code:

for _ in range(int(input())):
n=int(input())
s=input()
a,b=’ ‘,’ '
for i in range(0,n,2):
a+=s[i]
for i in range(1,n,2):
b+=s[i]
res1=’’.join(sorted(a))
res2=’’.join(sorted(b))
if res1==res2:
print(“YES”)
else:
print(“NO”)

if I call the empty strings a,b outside the loops i.e. at the beginning/first line then it does not work.

a,b=’ ‘,’ '
for _ in range(int(input())):
n=int(input())
s=input()
for i in range(0,n,2):
a+=s[i]
for i in range(1,n,2):
b+=s[i]
res1=’’.join(sorted(a))
res2=’’.join(sorted(b))
if res1==res2:
print(“YES”)
else:
print(“NO”)

Can anyone please explain to me why?

a,b=’’,’’ means you set both a and b to “,” right?
Doing that inside the for loop means you do that every single step of the loop. I guess the outer loop are your testcases?

Resetting a and b for every testcase is important, else you will keep appending to them even though they are already filled from other testcases.

1 Like

ohh… Thanks :raised_hands: