We are given a string X of even length, consisting only of characters 'S' and 'T'. Exactly half of the characters are 'S' and half are 'T'. The operation: repeatedly (10^{10000} times, essentially infinite) find the leftmost occurrence of substring "ST" in the current string X and remove both characters (i.e., remove that contiguous "ST" from the string). If no occurrence, do nothing. We need the eventual length of X after this infinite process (or after many operations until no "ST" remains, since once there are no "ST", nothing changes).
Essentially, we simulate removing all possible "ST" substrings in a leftmost greedy removal repeatedly. This is reminiscent of a reduction process like removing matching pairs, perhaps akin to a stack-based elimination: when we have 'S' and then 'T', they cancel? But note: the removal is always of the leftmost "ST" substring, and after removal, the string concatenates, possibly creating new "ST" occurrences. This is similar to repeatedly canceling adjacent S followed by T, but the leftmost condition suggests a deterministic process. However, we might think of it as: scanning from left to right, we can treat S as opening and T as closing? Actually, "ST" is like S before T, but T before S does not cause removal. So it's like we remove any S that is immediately followed by T. But after removal, adjacent characters become neighbors, possibly forming new ST.
Observation: The process is equivalent to repeatedly removing adjacent S-T pairs where S is left of T. This is similar to the classic problem of reducing a string of parentheses, where '(' and ')' cancel when '(' appears before ')'. In that context, we can think of S as '(' and T as ')'. The operation removes "()" which is analogous to "ST". But careful: In parentheses matching, we typically remove "()" pairs that are matching in a balanced way? Actually, the process described: repeatedly remove the leftmost occurrence of "ST". This is exactly the process of reducing a string by canceling adjacent S and T when S comes before T. This is similar to evaluating a string of S and T as a kind of stack: For each character, if it's 'S', push it; if it's 'T', and if the top of the stack is 'S', then pop that S and not push the T (i.e., they cancel). Otherwise, push the T? But is that correct? Let's test with examples.
Take X = TSTTSS. Let's simulate manually. Initially: T S T T S S.
Operation: find leftmost "ST": scanning: positions: 1-2: "TS" not; 2-3: "ST" yes (S at pos2, T at pos3). So remove those two characters. After removal, string becomes: T (remove S at 2, T at 3) so remaining: pos1: T, then pos4: T, pos5: S, pos6: S => "TTSS". Now we have "TTSS". Find leftmost "ST": scanning: 1-2 "TT" no; 2-3 "TS" no; 3-4 "SS" no; Actually positions: T T S S. Check pairs: 1-2: TT, 2-3: TS, 3-4: SS. No "ST". So process stops. Length = 4. Output 4. Good.
Now consider second example: SSTTST. Simulate: S S T T S T.
Leftmost "ST": scanning: 1-2: SS no; 2-3: ST yes (S at pos2, T at pos3). Remove them. New string: take S at pos1, then after removal skip pos2-3, then pos4: T, pos5: S, pos6: T => "S T S T"? Actually careful: original indices: 1:S,2:S,3:T,4:T,5:S,6:T. Remove 2-3 (S at 2, T at 3) => remaining: 1:S, 4:T,5:S,6:T => "STST". Now "STST". Find leftmost "ST": at positions 1-2: S T? Actually string: index1:S, index2:T? Wait "STST": characters: 1:S,2:T,3:S,4:T. So 1-2 is "ST", remove leftmost? Yes, remove characters 1 and 2. Then remaining: characters originally at 3 and 4: S,T => "ST". Then next operation: "ST" removed => empty. So length 0. Output 0.
Third example: TSSTTTSS => let's simulate: maybe result 4.
Now, if we think about the stack algorithm: For each character in the original string, if it's 'S', push it; if it's 'T', then if the stack is non-empty and the top is 'S', then pop (cancel); else push 'T'. After processing all characters, the remaining stack's size is the final length. Does that match the described process? Let's test.
For X = TSTTSS: Process: start empty stack.
Char1: T -> stack empty, push T => [T]
Char2: S -> push S => [T, S]
Char3: T -> top is S, so pop => stack becomes [T]
Char4: T -> top is T, push T => [T, T]
Char5: S -> push S => [T, T, S]
Char6: S -> push S => [T, T, S, S] => final stack size 4. That's the output 4. Good.
Second: SSTTST.
Process:
Char1: S -> push S => [S]
Char2: S -> push S => [S,S]
Char3: T -> top S, pop => [S]
Char4: T -> top S, pop => []
Char5: S -> push S => [S]
Char6: T -> top S, pop => [] => size 0. matches.
Third: TSSTTTSS.
Let's compute:
Char1: T -> push T => [T]
Char2: S -> push S => [T,S]
Char3: S -> push S => [T,S,S]
Char4: T -> top S, pop => [T,S]
Char5: T -> top S? Actually top is S? Wait stack: bottom->[T,S], top is S. So pop => [T]
Char6: T -> top T, push T => [T,T]
Char7: S -> push S => [T,T,S]
Char8: S -> push S => [T,T,S,S] => size 4. matches.
Thus the stack algorithm gives the final length. But we need to be sure that this algorithm exactly models the repeated leftmost removal process. This is a well-known fact: The operation of repeatedly removing "ST" (like canceling adjacent S before T) yields the same result as the stack-based elimination where S acts as an opening and T as a closing that cancels an S. It's analogous to the reduction of a string of parentheses removing matching "()" pairs, but here the matching condition is simply that a T cancels the nearest preceding S? Actually in the stack algorithm, when we encounter T, if there's an S on the stack, we pop it; otherwise we push T. That suggests that T's cancel S's that are most recent? But is the leftmost removal process equivalent to this? Let's think.
In the removal process, we always remove the leftmost "ST". This is similar to repeatedly canceling adjacent S and T, but not necessarily only adjacent? Actually the substring "ST" must be adjacent. However, after removals, characters that were not adjacent may become adjacent. The stack algorithm effectively cancels any S that is followed by a T, even if there are other characters between them? Actually, the stack algorithm cancels an S with a T when the T appears and there is an S in the stack (i.e., an unmatched S that came before, but there could be other T's in between? Wait, stack algorithm processes left to right: when we see T, if there is an S at the top of the stack, we pop that S; this effectively cancels that S and this T. This corresponds to removing a pair that is not necessarily adjacent in the original string, because between them there might be characters that got canceled earlier. But in the removal process, the removal of "ST" is always adjacent at the moment of removal. The stack algorithm is a known way to compute the result of repeatedly canceling "()" pairs (or similar) because it essentially simulates the process.
We can prove: Starting from the original string, process characters one by one. Whenever we see a T and the last unmatched character (i.e., top of stack) is S, then we can cancel them by removing the substring consisting of that S, possibly some characters between them that were already matched and removed, and then this T. In the actual process, after removing inner pairs, they become adjacent and can be removed. The stack algorithm gives the final string of unmatched characters, preserving order. And importantly, the process is confluent: final result is unique regardless of removal order (though here removal order is fixed as leftmost). However, since we have an operation count huge, it's effectively until no more ST. The result is indeed the irreducible string where no S appears immediately before a T. In other words, after fully reducing, the string will be of the form: some number of T's followed by some number of S's? Because if an S is left of a T, they'd form an ST. So in final string, all T's must come before any S? Let's check: If final string has any occurrence of S followed by T, that's an ST, so would be removed. So final string must have no S before T. That means all T's appear before all S's. So final string is of the form: T...T S...S. However, note that there might be other patterns? Actually, if we have any T after an S, that's S then T, which is forbidden. So indeed, in the final string, all S's are to the right of all T's. So it is a string consisting of some number of T's followed by some number of S's, with no interleaving. That's a necessary condition for no "ST". But is it sufficient? Yes, because any adjacent pair in such a string: if both are T, it's fine; both S, fine; T followed by S is "TS", not ST, so fine. So final string is of the form T^a S^b, where a and b are nonnegative integers. And the original total counts of S and T are equal (half and half). After removal, the total counts of S and T may change because each removal removes one S and one T. So the numbers of S and T removed are equal, so the difference between counts of S and T remains constant? Actually, removal removes one S and one T, so the difference (count(S) - count(T)) remains unchanged. Initially, count(S) = count(T) = n/2, so difference = 0. Therefore, after any number of removals, count(S) = count(T) still? Wait, careful: each removal removes exactly one S and one T. So the counts of S and T decrease by 1 each. So the difference count(S) - count(T) remains the same: initially 0, so after any removals it remains 0. Therefore, in the final string, count(S) = count(T). So a and b must satisfy a = b? Actually, if final string is T^a S^b, then count(T)=a, count(S)=b. Since they must be equal, we have a = b. So final string has equal numbers of T and S, all T's on the left, all S's on the right. But is that always achievable? Possibly, yes. Then final length = 2a. So we need to compute a = number of T left (which equals number of S left). That is equal to the number of unmatched T? Actually from stack algorithm, final stack contains some characters; they must be of the form some T's then some S's? Let's check: In the stack algorithm, we push S unconditionally; when T appears, if top is S, pop; else push T. So the stack always maintains an order such that all T's that are pushed are never followed by an S? Actually, consider the stack after processing: Since we only push S at the end, and when we push T, it's only when top is not S. But could we have an S above a T? Suppose stack currently is ... T (top). Then we see an S; we push S, so now stack becomes ... T, S. That would have T then S, meaning in the final string, we have a T followed by an S, which is "TS", not "ST". That's allowed. But later, if we see a T, and top is S, then we would pop that S, eliminating that TS pair? Actually, the T would cancel with the most recent S, which could be above a T. So the stack may contain interleaving patterns, but after complete processing, the stack cannot contain an S immediately above a T? Actually, consider final stack: it contains characters in order of their positions. Since no further cancellations possible, there should be no occurrence of S followed immediately by T (i.e., adjacent in the final string) because that would be an "ST". But does the stack algorithm guarantee that the final stack is free of adjacent S followed by T? Let's examine: Suppose final stack has ... S, T ... as consecutive entries. That would correspond to an S immediately followed by a T in the final string, which is "ST". That would contradict that we can't have any more "ST". However, does the stack algorithm ensure that this does not happen? Let's test: If we have S on stack and later we push T (because top is not S), then S and T become adjacent in the stack? Actually, when we push T, it goes on top. If the previous top was S, then we would have popped S instead (since encountering T with top S cancels). So we only push T when the top is not S, i.e., top is T or stack empty. So after pushing T, the top is T, and the element below could be S? That is possible: e.g., process S, then T (which cancels, so no), but to get a T after an S, we need to have S pushed, then later push T when top is not S. But if S is on top, we wouldn't push T; we'd pop. So S cannot be directly below a newly pushed T because at the moment of pushing T, the top is not S. So the element below top could be S if we had something like: push S (stack: S). Then push T? But top is S, so T would cancel, not push. So to have S then T in final stack, we need a scenario where after pushing S, we push something else that is not T? But only characters are S and T. So the only thing we can push after S is either S (push) or T (which would pop). So if we push S, top is S; next char T cancels. So the only way to have a T above an S is to have pushed T when top is T (so stack has T on top) and then later push S, which goes on top of T, giving T then S, not S then T. So final stack may have T followed by S, but never S followed by T. Indeed, stack order is such that all S's are always on the right of all T's? Let's analyze: The stack after processing will have a sequence where all T's appear before any S? Actually, consider the following: Process: T, S. Start: push T -> [T]; then S -> push S -> [T, S]. So stack ends with T then S (i.e., T followed by S). That's allowed because final string would be "TS", not "ST". So the final stack is of the form: some number of T's, then some number of S's. Because whenever an S appears, if there is any T on top? Actually, if there is T on top, S is pushed, resulting in ...T, S. That yields T then S. But could we later get an S before a T? That would require an S below a T, i.e., T on top of S. But T on top of S would mean that at some point after pushing S, we pushed T without popping the S. But that can't happen because if top is S, T would pop it. So we cannot have a T above an S if there is an S immediately below? However, could there be other characters in between? Suppose stack: S, T? Wait, we want T above S, i.e., stack from bottom to top: ... S, ... T? Actually, T above S means at some point S is lower, and later T is pushed on top. But as argued, when we push T, if top is S, we pop. So to push T on top of S, we need that at that moment top is not S. But if S is somewhere below, that's fine; we might have T on top of other T's, and then later push S, which goes above the T's, making S after T. So the only possible pattern is: the stack consists of a (possibly empty) sequence of T's, followed by a (possibly empty) sequence of S's. Let's prove: At any point, the stack never has an S below a T. Because suppose contrary: there exists an index i < j in the stack such that stack[i] = S and stack[j] = T. That would mean that when the T at position j was pushed, the top of the stack before pushing was something else (maybe S or T). If the top was S, then we would have popped that S, not pushed T. So the top was not S, so it was T or empty. So when we pushed T, the element just below it (if any) could be T or empty. So it's impossible to have an S directly below a T? But could there be an S two positions below a T? Suppose stack: bottom [S, T]. That would require that at some point we had S pushed, then later T pushed while top was not S. But after S is pushed, top is S, so the next character if it's T will pop S, not push T. So we can't have S then T in that order at all, even with other characters in between? Actually, if we have S, then later push T, but if there is any other character above S before T, that would mean after pushing S, we pushed something else that is not T? Only characters are S and T. So after S, the next character could be S (push another S) or T (pop). So if it's S, stack becomes [S, S]. Then top is S. Next character T will pop the top S, resulting [S]. So still no T above S. If we have S, then some T that pops, then later push T? But then the S is gone. So indeed, it's impossible to have an S lower than a T. Because any S that is pushed will either be popped by a later T before any T is pushed above it, or remain, but then any subsequent T will either pop it if it's top, or if it's not top, there must be some S on top to be popped first. Let's think: Could we have stack: [T, S]? That's T then S, which is allowed, and that has T below S. That's the reverse: T below S. So S above T is fine (T then S). The pattern we get is: all T's are at the bottom, then all S's on top. Because initially we might push some T's, then later push S's. Since S's can't be below T's? Actually S's can be above T's, as in [T, S] (T bottom, S top). So that means S's appear after T's in the stack order (which corresponds to later positions in the string). So indeed, the final stack is of the form: some number of T's, then some number of S's. Because if there is any S, it must be after all T's (i.e., no T after an S). Because suppose there is an S, and later a T is pushed. That T, when encountered, would see top = S (since the S is the most recent), so it would pop that S, eliminating the S and not push T. So a T cannot be pushed after an S without canceling it. Therefore, after processing the entire string, there cannot be any T that comes after an S in the stack. So the stack order is T's then S's. Good.
Thus final string = some number of T's followed by some number of S's. And since #S = #T initially and each removal removes one of each, final #S = #T. So the final counts must be equal. Let a = number of T left = number of S left. Then final length = 2a.
So the problem reduces to: Given the initial string with equal numbers of S and T, after performing this elimination process, what is the number of surviving S (or T)? Since final #S = #T = some value, we can compute that as: the number of S that never get canceled, equivalently, the number of T that never get canceled.
From the stack algorithm, final stack size = number of unmatched characters. Since final stack consists of T's and S's in equal numbers? Let's check: In the stack algorithm, final stack might contain both T's and S's. But does it guarantee that #T = #S? Let's test with example: TSTTSS gave final stack: [T, T, S, S] -> #T=2, #S=2, equal. Another: SSTTST gave empty. Another: TSSTTTSS gave [T, T, S, S] -> equal. Let's test with something else: Suppose X = TTTTSSSS. Process: all T's then all S's. Stack: T push, T push, T push, T push (since no S to cancel), then S: first S sees top T? Actually top is T, not S, so cannot pop; so we push S? Wait, according to algorithm, for S we always push. So after processing TTTT, stack = [T,T,T,T]. Then process S: push S => [T,T,T,T,S]; next S: push => [T,T,T,T,S,S]; next S: push; next S: push; final stack = [T,T,T,T,S,S,S,S]. That has 4 T and 4 S, equal. Indeed, final string would be TTTTSSSS, and there is no ST because all S are after T, but there are TS pairs (which are fine). So no removals occur. So final length = 8. That matches.
Consider X = S S S T T T? Actually equal numbers: "SSSTTT". Process: first three S: stack [S,S,S]. Then T: first T sees top S, pop => [S,S]; second T pop => [S]; third T pop => []; final empty. So length 0. That matches.
Now consider something like "T S S T". That's length 4, 2 S, 2 T. Process: T push [T]; S push [T,S]; S push [T,S,S]; T sees top S pop => [T,S]; final stack [T,S] -> T then S, counts: T=1, S=1, equal. So length 2. Indeed, original "TSST": we can simulate removal: leftmost "ST"? String: T S S T. Look for ST: positions: 1-2: TS no; 2-3: SS no; 3-4: ST yes (S at 3, T at 4). Remove those: leaves T S (positions 1 and 2). That is "TS". No ST, length 2. So matches.
Thus indeed final string always has equal numbers of T and S, in that order. So length = 2 * (number of surviving S) = 2 * (some value). So we can compute the final length as the number of characters remaining after stack elimination, which is simply the size of the final stack.
But we need to output the length, not necessarily compute stack explicitly (which would be O(n) anyway). However, constraints up to 200,000, so O(n) is fine. But we can also compute the number of unmatched S or T more directly.
Alternatively, note that each removal removes one S and one T. So the number of removals = (n - final_length)/2. So final_length = n - 2*k, where k is the number of removals. So we need to compute k.
We can think of the process as: we have a string of S and T. Remove "ST" repeatedly. This is similar to finding the maximum number of non-overlapping cancellations? But since removals can cascade, the total number of removals is determined by the string structure.
Consider the stack method: final length = |stack|. Alternatively, we can think in terms of a balance: treat S as +1, T as -1? But careful: In parentheses matching, '(' as +1 and ')' as -1, with the rule that we cancel when we see a closing that matches an opening. For "ST" cancellation, S is like '(' and T like ')', but the rule is that a T cancels the most recent S if any. That's exactly the same as parentheses matching: '(' push, ')' if stack has '(' pop, else push? Wait in parentheses matching, if we have a string of '(' and ')', the standard algorithm to remove matching pairs is: keep a stack; for '(' push; for ')' if stack top is '(' pop, else push ')'. That yields the unmatched parentheses. That's exactly our algorithm with S='(', T=')'. So final length = number of unmatched parentheses. But in our case, the condition for removal is "ST", not "()"? Actually in parentheses, removal of "()" is similar, but note that in parentheses, a matching pair is '(' then ')', which corresponds to S then T. So indeed it's identical. So we have a classic problem: given a string of '(' and ')' with equal numbers of each, after repeatedly removing "()" substrings (greedily leftmost), what's the final length? But careful: In parentheses reduction, the typical rule is to repeatedly remove "()", but it's known that the result is the same as removing all matched pairs, leaving the unmatched ones. And indeed, the final string consists of some ')' then some '('? Actually, for parentheses, the unmatched ones after this process would be something like: ")))((("? Let's consider: If we treat '(' as S and ')' as T, then after elimination, the final string is all T's then all S's (since S = '('? Actually we had S corresponding to '('? In our mapping, S is '('? Wait we had S corresponds to '('? In the process, we remove "ST". So S is the first character, T second. In parentheses, we remove "()", so '(' corresponds to S, ')' corresponds to T. So indeed S is '(' and T is ')'. In parentheses reduction, after fully canceling matching pairs, the remaining string is of the form "))...))(((...((", i.e., some closing parentheses followed by some opening parentheses. Because if there is an opening before a closing, they'd match and cancel. So the remaining opens are all to the right of all closes. That matches: T (closing) then S (opening). So yes.
Thus the problem reduces to: Given a string of '(' and ')' with equal number of each, after removing all matching pairs (by repeatedly canceling adjacent "()"?), the remaining length is twice the number of unmatched parentheses of each type? Actually, the number of unmatched opens = number of unmatched closes, because total counts equal? Let's check: In a parentheses string, after canceling matching pairs, the number of unmatched ')' (closing) and unmatched '(' (opening) are not necessarily equal; but the total counts of '(' and ')' originally can differ. However, here they are equal initially. In that case, the number of unmatched ')' equals the number of unmatched '('? Let's check: Suppose we have string "))) (((" with equal numbers? Actually that would be 3 ) and 3 (, but after cancellation? But we need to apply the process: For "))) (((" there is no "()", so nothing cancels, so remaining string is "))) (((" which has 3 ) and 3 (; unmatched counts are equal. In general, for any string, after removing all matching pairs, the remaining string is of the form )^a (^b. The total count of '(' originally is (matched opens) + b; total count of ')' originally is (matched closes) + a. Since matched opens = matched closes = k, we have total '(' = k + b, total ')' = k + a. Since total '(' = total ')' (given), we have k+b = k+a => a = b. So indeed the numbers of unmatched closing and opening are equal. So final length = 2a.
Thus we can compute a by scanning and using a counter: let balance be something? Classic algorithm: keep a stack or simply count the number of unmatched S? Actually we can compute the number of matched pairs directly: This is essentially the number of valid parentheses pairs that can be eliminated. The number of unmatched S (or T) can be found by a simple counter: we maintain a counter 'open' which counts the number of S that have not been matched by a T yet. When we see an S, increment open. When we see a T, if open > 0, then we match this T with a previous S, so decrement open (representing a cancellation). Else, open is 0, this T is unmatched (so we might need to count it separately). But we need to count both unmatched S and unmatched T. However, we can compute the number of matched pairs: each time we see a T and open>0, we match one pair. So total matches = number of such T's. Then final length = initial length - 2matches. That is: n - 2 * (number of times we saw a T when open>0). But careful: Is the number of matches equal to the number of such T's? Let's test with "TSTTSS": Initially open=0. Char1: T -> open=0, no match, but we need to note that this T is unmatched? In the stack algorithm, we push T when open=0. So open remains 0. Char2: S -> open=1. Char3: T -> open>0, so match, open-- => 0. Char4: T -> open=0, no match, treat as unmatched T. Char5: S -> open=1. Char6: S -> open=2. So matches count = 1 (only char3). But final length from simulation is 4, and n=6, so 6-21=4, matches. Good.
Second: SSTTST: open=0; S->1; S->2; T-> match, open=1; T-> match, open=0; S->1; T-> match, open=0. matches = 3? Actually we matched at char3, char4, char6 = 3 matches. n=6, 6-6=0, correct.
Third: TSSTTTSS: open0; T: open0; S: open1; S: open2; T: match open1; T: match open0; T: open0? Actually char5: T, open=0 -> no match, unmatched; char6: T? Wait there are 8 chars: positions: 1:T,2:S,3:S,4:T,5:T,6:T,7:S,8:S. Let's recompute: open=0; c1:T => no match, open stays 0; c2:S => open=1; c3:S => open=2; c4:T => match, open=1; c5:T => open>0? Actually open=1, so match, open=0; c6:T => open=0, no match; c7:S => open=1; c8:S => open=2. matches: at c4 and c5: 2 matches. n=8, 8-4=4, correct.
Thus number of matches (i.e., number of removals) = number of times we encounter a T while open > 0. This is equivalent to counting the number of T's that are matched with a preceding S. This is essentially the number of valid pairs in the parentheses sense.
But wait, is it always the case that the total matches computed this way equals the number of pairs removed in the infinite process? Let's verify with more complex strings. For parentheses, the number of matched pairs is the size of the maximum possible matching? Actually, the process of repeatedly removing "()" yields all possible matched pairs, i.e., the total number of pairs that can be matched in a valid parentheses matching (the standard algorithm yields the number of matched pairs, and all matched pairs will eventually be removed). Indeed, the algorithm that uses a counter (open) counts the number of times we see a closing parenthesis that can match an open. This gives exactly the number of pairs that are matched in the usual sense (the maximum number of nested matching pairs). So yes.
Thus we can compute matches = sum over characters: if char == 'S' then open++ ; else if char == 'T' then if open > 0 then matches++, open-- else do nothing (or could treat as unmatched). After scanning, final length = n - 2*matches.
But is that always correct? Let's test with a tricky case: Suppose X = "STST". n=4. Process: open=0; S: open=1; T: open>0 => matches=1, open=0; S: open=1; T: open>0 => matches=2, open=0. So matches=2, n-4=0, final length 0. That matches simulation: remove leftmost ST (positions1-2) -> "ST"? Actually after first removal, we get "ST" (positions3-4? Wait original: indices:1:S,2:T,3:S,4:T. Remove leftmost ST at (1,2) -> string becomes characters 3,4: S,T => "ST". Then remove that -> empty. So yes.
Another: "TSTS". n=4. open=0; T: no match, open0; S: open1; T: open>0 => matches=1, open0; S: open1. matches=1, final length=4-2=2. Let's simulate: "TSTS": leftmost ST? positions: 1-2 "TS" no; 2-3 "ST" yes (S at2, T at3). Remove -> remaining: T (pos1) and S (pos4) => "TS". No ST, length 2. Correct.
Thus the simple counter works.
But wait, is there any scenario where the greedy leftmost removal might yield a different number of removals than the maximum matching? For parentheses, repeatedly removing "()" (the substring) is known to remove all matched pairs, because any matched pair will eventually become adjacent after removals of inner pairs. This is analogous to the classic "remove all valid parentheses pairs" algorithm. So it's fine.
Thus the answer can be computed as:
n = len(X)
open = 0
matches = 0
for each char c in X:
if c == 'S':
open += 1
else: # c == 'T'
if open > 0:
matches += 1
open -= 1
final_length = n - 2*matches
Alternatively, we can compute directly: final_length = 2open_remaining? Actually after scanning, open might be >0, indicating unmatched S. But also there could be unmatched T that we didn't count. But we can compute final length as (open_remaining) + (unmatched_T_count). However, note that open_remaining after scanning equals the number of unmatched S. Also, the number of unmatched T is something like: total_T - matches. Since total_T = n/2, matches = number of matched T. So unmatched_T = n/2 - matches. Similarly, unmatched_S = n/2 - matches. So total unmatched = 2(n/2 - matches) = n - 2*matches. So consistent.
Therefore answer = n - 2*matches.
But we must be careful: open counts current unmatched S. At the end, open will be number of unmatched S. So final length = 2open? Since unmatched_S = open, and unmatched_T = n/2 - (total matches)?? Actually total matches is the number of matched pairs, which equals number of matched S and T. So unmatched_S = total_S - matches = n/2 - matches. But is open after scanning equal to unmatched_S? Let's check: open is incremented for each S, decremented for each matched T (when we see T and open>0, we decrement open). So open after scanning is exactly (#S - #matched T). But #matched T = matches, and each matched T cancels one S. So open = n/2 - matches. Yes. So unmatched_S = open. And unmatched_T = #T - matches = n/2 - matches. So total = 2open. So final length = 2open. So we could also compute open and output 2open. That is the same as n - 2*matches.
Thus we can either count matches or track open, whichever.
But careful: In the scanning algorithm, when we see a T and open>0, we decrement open and count a match. If we don't count matches, we can just do: if c == 'S': open++; else if open>0: open--; else nothing. Then at the end, final length = 2open? Wait, after processing all characters, open will be (#S - #matched T). But that's the number of unmatched S. However, there are also unmatched T, which we did not store. So final length = unmatched_S + unmatched_T. unmatched_T = #T - #matched T = n/2 - (#S - open)?? Let's compute. #S = n/2, #matched T = number of times we decremented open, which is (initial #S? Actually we decrement open exactly when we see a T and open>0. Let matched_T = number of such decrements. Then open_final = #S - matched_T. Also total_T = n/2. So unmatched_T = n/2 - matched_T. So total = open_final + (n/2 - matched_T). But matched_T = #S - open_final = n/2 - open_final. So unmatched_T = n/2 - (n/2 - open_final) = open_final. So total = open_final + open_final = 2open_final. So indeed, the final length is twice the value of open after processing. Let's verify with examples.
X = TSTTSS: Process without counting matches, just open: start open=0. T: open>0? no, do nothing -> open=0. S: open=1. T: open>0, so open-- =>0. T: open=0, do nothing. S: open=1. S: open=2. Final open=2 => 2*2=4, correct.
X = SSTTST: open=0; S:1; S:2; T: open>0 =>1; T: =>0; S:1; T: =>0; final open=0 =>0.
X = TSSTTTSS: open=0; T:0; S:1; S:2; T:1; T:0; T:0; S:1; S:2; final open=2 =>4.
X = "TSTS": open=0; T:0; S:1; T:0; S:1; final open=1 =>2. Good.
So we can simply do: open = 0; for each char: if char=='S': open++; else if open>0: open--; // else if char=='T' and open==0: do nothing. Then answer = 2*open.
But wait: is there any case where a T that appears when open==0 should be counted as unmatched, and later an S might match with it? No, because the operation only removes ST, i.e., S before T. A T before an S does not cancel. So unmatched T cannot be canceled later by a subsequent S because that would be TS, not ST. However, if later there is an S, could they become adjacent after some removals and form ST? For a T that is earlier than an S, the pair is TS, not ST. But after removals of intermediate characters, it's possible that a T and a later S become adjacent in the order T then S, which is TS, not ST. To form ST, we need S before T. So a T that appears before an S will never be part of an ST pair because the S is after the T. However, could a T that is initially unmatched later become adjacent to an S that is before it? That would require an S that is left of the T. But if we have open>0 when we see T, we match it with a prior S, so that T is matched. If open==0, there is no S before it that hasn't been matched, so any S that appears later is to the right, thus T is before S, so can't form ST. So indeed, unmatched T are permanent. And unmatched S are also permanent because any later T would try to cancel them? Actually unmatched S are S that are not followed by enough T to cancel them (or they are followed by T but those T might have been used to cancel other S? Let's think: Unmatched S are S that never get canceled because there are insufficient T after them. In the scanning, open counts the number of S that have not yet been matched by a subsequent T. At the end, these S are unmatched and will remain, and any T after them? Actually if there are any T after the last S, they would have been used to cancel S if possible; if there are still S left, it means there were fewer T after those S. So those S remain, and any T that remain are those that appeared before any S that could cancel them? Actually as we argued, unmatched T are those T that appear when open==0, i.e., when there is no preceding unmatched S to cancel them. Those T will remain. And they are all to the left of any remaining S? The final order is T's then S's. So open after scanning gives the number of remaining S. And the number of remaining T is also open. So answer is 2*open.
Thus the algorithm is trivial O(n).
But wait, let's double-check with more random cases to ensure no oversight. Consider X = "ST"*k, i.e., alternating starting with S. n=2k. Scanning: open: S->1, T-> open-- =>0, repeat. So open ends 0, answer 0. That makes sense: all pairs cancel.
Consider X = "TS"*k. n=2k. Scanning: T: open0; S: open1; T: open0; S:1; ... final open=1 if k odd? Actually if k=1: "TS": open0->T nothing, S->open1 => final open=1 -> answer=2. But is that correct? String "TS": there is no "ST", so no removal, length remains 2. So answer=2, correct. If k=2: "TSTS": we already did, open final=1 => answer=2, correct. If k=3: "TSTSTS"? Actually "TS"*3 = "TSTSTS". Let's simulate: T,S,T,S,T,S. Scanning: T:0; S:1; T:0; S:1; T:0; S:1 => open=1 -> answer=2. Simulate removal: "TSTSTS". Find leftmost ST: positions: 1-2 "TS" no; 2-3 "ST" yes (S at2, T at3). Remove -> string: T (1), S(4), T(5), S(6) => "TSTS". Then as before reduce to "TS" => length2. So yes.
Consider X = "TTSS": n=4. Scanning: T:0; T:0; S:1; S:2 -> open=2 -> answer=4. That matches: no ST, so remains 4.
Consider X = "SSTT": n=4. Scanning: S:1; S:2; T:1; T:0 -> open=0 -> answer=0. Indeed "SSTT": leftmost ST at positions2-3? Actually "SS TT": positions1-2 "SS",2-3 "ST"? Wait string:1:S,2:S,3:T,4:T. Leftmost ST is at (2,3). Remove -> string becomes S (1), T (4) => "ST". Then remove -> empty. So answer 0.
Consider X = "TSSSTT"? Not equal counts? But constraints say half S half T, so length even, counts equal. So need to ensure total S = total T. So we can rely on that.
Thus the solution is straightforward.
But is there any nuance regarding the leftmost removal and the fact that we perform it 10^10000 times? That effectively ensures we continue until no ST. But maybe the process might not terminate? It will always terminate because each operation reduces length by 2, and length is finite. So it will definitely terminate after at most n/2 steps. So final state is reached well before 10^10000 operations.
Thus answer is simply: 2 * (number of S that are not matched by a later T in the left-to-right scanning matching).
Alternatively, it's the number of characters that cannot be paired as "ST" in the elimination process.
We can implement as described.
Complexity: O(|X|).
Now let's think about possible pitfalls: The input length can be up to 200,000, so using Python, reading string and iterating is fine. Memory is fine.
Edge cases: smallest length 2: possible strings: "ST" -> answer 0; "TS" -> answer 2. Both satisfy. Also "SS" and "TT"? But those violate half S half T? "SS": length 2, half S half T means 1 S and 1 T. So not allowed. So only strings with equal number of S and T.
Thus we can implement.
Now, is the stack algorithm always correct given the leftmost removal? Let's attempt to prove more formally to convince ourselves, though for solution we can rely on known reasoning.
Proof sketch: The operation repeatedly removes the leftmost "ST". Consider the process: at each step, we look for the first occurrence of S followed immediately by T and remove both. This is equivalent to scanning from left to right with a stack: when we encounter S, we push it; when we encounter T, if the top of the stack is S, then that S is the most recent unmatched S, and the current T forms an ST with that S after removing any inner matched pairs. The removal of leftmost ST essentially corresponds to canceling the innermost? Actually leftmost ST may not be the innermost; but by always choosing the leftmost, it eventually leads to the same final state as the stack reduction. This can be proved by induction on the string length or by noting that the reduction is confluent (Church-Rosser property) for this rewriting system; any sequence of removals leads to the same irreducible string. So we can compute using the stack method.
Thus code: read X; open=0; for c in X: if c=='S': open+=1 else: if open>0: open-=1; print(2*open)
But careful: if we only decrement open when open>0 and c=='T', that's correct. But what about the case where c is 'T' and open==0? We do nothing. So open remains 0.
That yields the number of unmatched S after the scan. Then answer=2*open.
Let's test again with a string that has many T's initially: "TTT...SSS..." all T then all S. Then open after scanning: initially 0 for all T's, open stays 0; then for each S, open increments; no T after to decrement; final open = #S = n/2; answer = n. That matches because no ST in such string.
If all S then all T: "SSS...TTT...", open increments to n/2, then each T decrements, open becomes 0; answer=0.
Thus good.
We must ensure to use integer arithmetic.
Thus solution is done.
Now, there is another way: answer = |X| - 2 * min_{prefix} something? Actually it's related to the maximum number of "ST" pairs we can form, which is essentially the number of matched pairs. This is similar to computing the number of times we can perform the operation. That number is the number of pairs where an S appears before a T, with the condition that they can be matched without crossing? Actually it's exactly the number of matched pairs in the usual parentheses matching (non-crossing). But since S and T are just two types, it's the number of pairs (S,T) such that each S is matched with a T that occurs after it, and each T is matched with an S before it, without crossing? But the stack algorithm yields a matching where each T matches the most recent unmatched S. That yields a non-crossing matching.
Thus answer computed.
Now, we need to produce final length. So output 2*open.
Implementation details: In Python, we can use sys.stdin.readline().strip() to read X. Then iterate.
But wait, input constraints: the string contains only 'S' and 'T', uppercase. So fine.
Time: O(n).
Now, let's think about whether we can also derive formula from counts of something like: answer = 2 * |#S in prefix - #T in prefix|_max? Actually, for parentheses, the number of unmatched parentheses is something like: after cancellation, the number of remaining opening parentheses is the maximum excess of openings over closings? Actually, in parentheses matching, the number of unmatched '(' is total '(' minus matched pairs; the number of unmatched ')' is total ')' minus matched pairs. But we have equal totals, so unmatched '(' = unmatched ')'. There is also a relationship with the minimal balance. But the stack method is simplest.
So final code:
def solve():
import sys
X = sys.stdin.readline().strip()
open = 0
for c in X:
if c == 'S':
open += 1
else: # T
if open > 0:
open -= 1
print(2*open)
That's it.
But wait, is there any scenario where an S and a T that are not adjacent originally, but after other removals become adjacent and form ST, could be missed by the stack algorithm? No, the stack algorithm accounts for that because the stack elimination essentially simulates that. So it's fine.
Now, double-check with more random tests, maybe generate random strings of S and T with equal counts, simulate both methods to be sure. We'll do mental test.
Example: X = "STTSSS"? Not equal? 2 S? Actually let's pick length 6: 3 S, 3 T. Random: "S T T S S T" = "STTSST". Simulate greedy removal manually? Might be messy but we trust.
Compute open: S:1; T: open>0 =>0; T: open=0; S:1; S:2; T: open>0 =>1; final open=1 -> answer=2. Let's try simulation: "STTSST" (positions:1:S,2:T,3:T,4:S,5:S,6:T).
Step1: find leftmost ST: scan: 1-2: ST (yes) because S at1, T at2. So remove positions1-2. New string: positions3:T,4:S,5:S,6:T => "TSST".
Now "TSST": scan: 1-2: TS no; 2-3: SS no; 3-4: ST yes (S at3? Actually indices: 1:T,2:S,3:S,4:T? Wait after removal: we have original 3:T,4:S,5:S,6:T -> string: T S S T. So positions:1:T,2:S,3:S,4:T. Leftmost ST: check 1-2: TS no; 2-3: SS no; 3-4: ST yes (S at3, T at4). Remove positions3-4? That's S at3 and T at4. After removal, string becomes T (1) and S (2) => "TS". No ST. So final length 2. matches answer 2.
Another: "TSTSTS"? That's length 6? Actually "TSTSTS" has 3 T and 3 S? Let's count: T,S,T,S,T,S => 3 T, 3 S. open: T:0; S:1; T:0; S:1; T:0; S:1 => open=1 -> answer=2. Simulate? We already did similar.
Another: "SSTTTS"? That's 3 S, 3 T? "SSTTTS": S,S,T,T,T,S. Count S:1,2,6 => 3; T:3,4,5 =>3. open: S:1; S:2; T:1; T:0; T:0; S:1 => open=1 -> answer=2. Simulate: "SSTTTS": Find leftmost ST: positions? 1-2:SS no; 2-3: ST? S at2, T at3 => yes. Remove 2-3 => string: S (1), T(4), T(5), S(6) => "STTS". "STTS": 1-2: ST (S at1, T at2) => remove => string: T(3), S(4) => "TS". Final length 2. Good.
Another: "TTSSTT"? Count: T,T,S,S,T,T: 2 S? Actually 2 S, 4 T? Not equal; need equal. So not valid.
All good.
Thus answer is correct.
Now, we need to output length as integer.
Potential pitfalls: None.
Now, let's also consider if the leftmost removal infinite process could ever get stuck in a cycle? No, because each operation reduces length by 2, so it's strictly decreasing until no ST. So termination is guaranteed.
Thus final answer.
We'll now produce the final solution explanation and code.
But wait, we have to consider that the operation is performed 10^10000 times, which is far more than needed. So we just need final state.
Thus solution:
- Read X.
- Initialize variable cnt = 0 (number of unmatched S).
- For each character c in X:
- if c == 'S': cnt += 1
- else: if cnt > 0: cnt -= 1
- Print(2 * cnt)
Edge case: Input may have newline.
Test with provided examples.
Example1: TSTTSS -> cnt: T:0; S:1; T:0; T:0; S:1; S:2 -> cnt=2 -> 4, matches.
Example2: SSTTST -> cnt: S:1; S:2; T:1; T:0; S:1; T:0 -> cnt=0 -> 0.
Example3: TSSTTTSS -> cnt: T:0; S:1; S:2; T:1; T:0; T:0; S:1; S:2 -> cnt=2 -> 4.
All good.
Thus answer.
Now, we could also think about whether the order of removal matters. But we already accounted.
So we'll code.
Time complexity O(N), memory O(1).
Now, final code. We'll use Python's sys.stdin.
We'll also handle possible spaces, but not needed.
Now, provide final answer. ```python
import sys
def solve() -> None:
X = sys.stdin.readline().strip()
unmatched_S = 0 # number of S that are not yet matched by a later T
for ch in X:
if ch == 'S':
unmatched_S += 1
else: # ch == 'T'
if unmatched_S > 0:
unmatched_S -= 1
print(2 * unmatched_S)
if name == "main":
solve()