Help me in solving SUSSTR problem

My issue

Please help

My code

# cook your dish here
from collections import deque

def solve_game(S):
    T = deque()
    turn = 0  # 0 for Alice, 1 for Bob
    
    while S:
        if turn == 0:  # Alice's turn (she picks the first character)
            if S[0] < S[-1]:
                T.append(S[0])  # Alice appends to the back if the first character is smaller
            else:
                T.appendleft(S[0])  # Otherwise, Alice appends to the front
            S = S[1:]  # Remove the first character
        else:  # Bob's turn (he picks the last character)
            if S[0] > S[-1]:
                T.append(S[-1])  # Bob appends to the back if the last character is larger
            else:
                T.appendleft(S[-1])  # Otherwise, Bob appends to the front
            S = S[:-1]  # Remove the last character
        
        # Alternate turns
        turn = 1 - turn
    
    return ''.join(T)

# Input handling
T = int(input())  # Number of test cases
for _ in range(T):
    N = int(input())  # Length of the string
    S = input().strip()  # The binary string S
    print(solve_game(S))

Learning course: Data structures & Algorithms lab
Problem Link: https://www.codechef.com/learn/course/muj-aiml-dsa-c/MUJADSAC27/problems/SUSSTR