We need to count number of substrings of a given string S of length N that are sorted (non-decreasing lexicographically: each character ≤ next). N up to 1e6 per test case, T up to 10, total N up to maybe 10^6? Usually T * N can be up to 10^6? But not guaranteed, but we must be efficient O(N) per test case.
We need to count all substrings that are sorted. Equivalent: count number of contiguous subarrays where the sequence of characters is non-decreasing.
Observation: A substring is sorted iff it is a contiguous segment where S[i..j] satisfies S[k] ≤ S[k+1] for all k from i to j-1.
Thus we can find maximal runs of non-decreasing contiguous segments. For example, we can scan S and identify increasing runs: when we find a position where S[i] > S[i+1], that breaks the non-decreasing property. So the string can be partitioned into maximal substrings that are sorted. For each such maximal run of length L (i.e., a contiguous block where each adjacent pair is non-decreasing), any substring inside that run is also sorted because the substring inherits the property? Actually careful: If we have a run of non-decreasing adjacent pairs, then any contiguous subsegment of that run will also have non-decreasing pairs because the condition is local between consecutive characters; if we take a subset, the condition holds for the adjacent pairs within that subset. So all substrings fully contained within a maximal sorted run are sorted. But what about substrings that cross boundaries? They would contain a position where S[i] > S[i+1], thus not sorted. So the total number of sorted substrings = sum over all maximal non-decreasing runs of (len*(len+1)/2) where len is the length of the run.
Let's test: For "abc": runs: whole string is one run length 3, so 3*4/2=6, matches.
For "bba": Let's parse: S = b b a. Check pairs: b to b: equal, ok. b to a: b > a? 'b' > 'a', so break. So runs: first run "bb" length 2, second run "a" length 1. Sum: 23/2=3, plus 12/2=1, total 4. Matches sample.
For "abac": S = a b a c. pairs: a to b: ok (a<=b). b to a: b > a, break. a to c: a <= c, ok. So runs: "ab" length 2? Actually careful: The run includes contiguous characters where each adjacent pair is non-decreasing. Starting at index 0: a to b ok, then b to a not ok, so first run is "ab" of length 2? But note: "ab" is indices 0-1. Next start at index 1? Actually after break, we start new run at index 1? The break occurs between index1 and index2 (b and a). So index1 is the end of first run? Typically we consider runs of maximum length: We start at index0, include index0 and index1 because pair0 ok, pair1 fails, so run indices 0..1 length 2. Next start at index2 (a): check index2 to index3: a to c ok, and no further, so run indices 2..3 length 2. So runs lengths: 2 and 2. Sum: 3 + 3 = 6? Actually 2*3/2=3 each, total 6. But sample answer is 6. But wait: The sample gave sorted substrings: a, b, a, c, ab, ac. That's 6. Yes.
But check: In the sample explanation for test case #3, they list substrings of "abac": a, b, a, c, ab, ba, ac, aba, bac, abac. Sorted ones: 'a', 'b', 'a', 'c', 'ab', 'ac'. That's 6. So our method gives 6.
For "zyx": S = z y x. pairs: z to y: z>y break; y to x: y>x break. So runs: "z" length1, "y" length1, "x" length1. Sum=1+1+1=3. matches.
So indeed it's simply sum of len*(len+1)/2 over runs of non-decreasing adjacent characters.
Thus algorithm: for each test case, iterate through S, track current run length starting at 1 (or count consecutive segments). When we encounter a character, we start new run. Actually standard: initialize count=1? Let's design:
Let total = 0
Let run_len = 1 (first character considered a run of length 1)
For i from 1 to N-1:
if S[i] >= S[i-1]: // non-decreasing
run_len += 1
else:
total += run_len*(run_len+1)//2
run_len = 1
After loop, add last run: total += run_len*(run_len+1)//2
Works.
Complexities: O(N) per test case.
But need to be careful about N up to 1e6, T up to 10, sum N up to maybe 10^6? Usually constraints may allow sum up to 10^6. Even if sum up to 10^7, O(N) fine.
Implementation details: Use long long (64-bit integer) for total.
Edge Cases: N=0? Not possible. N=1, run_len=1, total = 1.
All good.
But wait: is it always true that any substring within a non-decreasing run is sorted? Yes because the property is transitive? Actually check: For substring within a run, adjacent pairs are a subset of the original adjacent pairs which are all non-decreasing. So yes.
Thus solution is straightforward.
But sometimes there is a nuance: The condition is lexicographically sorted, meaning each character is ≤ next. This matches non-decreasing.
Thus answer.
But the problem might be trickier if they consider substrings of length 1 are always sorted. So our method counts them.
So implement accordingly.
Now we should write code.
But is there any case where a substring crossing runs could be sorted? Suppose S = "ab" and "ba"? Actually if crossing a break where S[i] > S[i+1], then that pair is decreasing, so the substring that includes that pair will have a decreasing adjacent pair. So it can't be sorted. So crossing runs never sorted.
Thus method holds.
Now, think about potential pitfalls: The input string length N may be up to 10^6, so we need to read efficiently, using fast I/O in C++ or Java. In Python, input reading may be okay with sys.stdin.read.
But constraints: N up to 1e6, T up to 10, so total input size up to 10 million characters, which is okay in Python with sys.stdin.buffer.
But need to be careful about integer operations: run_len*(run_len+1)//2 may be large: run_len can be up to N (1e6), product ~1e12, fits in Python int but we need 64-bit; Python int is arbitrary precision, fine.
Now, implement.
But wait: The sample input has a test case: "zyx" and sample output 3. They wrote "zyx" but in the description they have "SAMPLE INPUT" with "3" then "zyx"? Actually they have:
3
zyx
But in the sample they have "zyx" not "zxy"? Let's examine: "SAMPLE INPUT ... 3 zyx" then explanation says "Substrings of zxy are: ..." That's an inconsistency but answer matches 3.
Thus ok.
We'll implement.
Now, double-check: Could there be any situation where a substring not wholly inside a run could be sorted if the break is at the boundaries? For example, substring starting after the break and ending before the break? No crossing break. So not.
Thus simple.
Thus answer: sum over runs.
Implementation:
def count_sorted_substrings(s):
total = 0
run_len = 1
for i in range(1, len(s)):
if s[i] >= s[i-1]:
run_len += 1
else:
total += run_len * (run_len + 1) // 2
run_len = 1
total += run_len * (run_len + 1) // 2
return total
Now we must handle multiple test cases.
Edge Cases: s empty? Not present.
Now, about reading input: The first line T. Then for each test case, read N (int) and then S. But note that S may contain newline. Could have spaces? No, it's a string of lowercase letters.
In Python, we can use sys.stdin.readline() to read lines. But better to use sys.stdin.buffer.read().split() to get tokens. Since N and S are separate, we can parse tokens. Because N is given then S on next line. However, sometimes S may be given on same line? Problem says second line contains S. So safe.
So we can:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it)) # may not be needed if we read S's length, but we can ignore
s = next(it).decode()
# but careful: s could be bytes, so decode. Actually if we split, we get bytes, decode to str.
# Or we can keep as bytes and compare ASCII values; but decode is fine.
# However, s length should be n, but we can just use len(s).
total = 0
run_len = 1
for i in range(1, len(s)):
if s[i] >= s[i-1]:
run_len += 1
else:
total += run_len * (run_len + 1) // 2
run_len = 1
total += run_len * (run_len + 1) // 2
out_lines.append(str(total))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
But careful: The split() on whitespace will treat the string S as one token, fine. We need to ensure that there is no newline inside S. It's just a string.
Thus that's the solution.
But let's think about potential optimization: The loops are fine.
Now, let's test with given samples.
Test1: "abc": run_len=1->compare a,b: a<=b -> run_len=2; compare b,c: b<=c -> run_len=3; end: total=3*4/2=6.
Test2: "bba": a,b? Actually s[0]='b', s[1]='b': b<=b -> run_len=2; s[2]='a': compare s[1]='b' and 'a': b > a -> else: total += 23/2=3; run_len=1; end: total+=12/2=1 =>4.
Test3: "abac": s[0]='a', s[1]='b': ok run_len=2; s[2]='a': compare s[1]='b','a' -> b>a: total+=3? run_len=2 =>3; run_len=1; then s[3]='c': compare s[2]='a','c' -> a<=c: run_len=2; end total+=2*3/2=3 =>6.
Test4: "zyx": compare z,y: z>y -> total+=1 (run_len=1) => total=1; run_len=1; compare y,x: y>x -> total+=1 => total=2; run_len=1; end total+=1 =>3.
Matches.
Thus solution.
But wait: There's a nuance: The definition says "lexicographically sorted if si ≤ si+1 where 1 ≤ i ≤ N-1". That's exactly non-decreasing. So correct.
Now, just ensure to use 64-bit integer: In Python it's fine. In C++ we'd use long long.
So the answer is straightforward.
Given the caution, they want to avoid overflow in languages like C++.
Thus final answer.
But maybe there is a twist: The problem is from some platform where they might expect a different interpretation? Let's double-check the sample #3: They list sorted substrings: a, b, a, c, ab, ac. Indeed these are all substrings within runs: "a" (first a) from first run? Actually "a" at index0 is in first run; "b" index1; "a" index2 is second run; "c" index3; "ab" indices0-1; "ac" indices2-3. Works.
Thus algorithm is correct.
Now we should provide explanation and code.
But is there any scenario where a non-decreasing run may be defined differently? For instance, if string is "aaab", is "aaab" sorted? a<=a<=a<=b, yes. So run includes whole string. Good.
If string is "abca": check pairs: a<=b, b<=c, c>a? Actually c > a, so run breaks. So runs: "abc" length3, and "a" length1. Sorted substrings: all substrings of "abc" (6) plus "a" (1) =7. Let's enumerate substrings of "abca": a,b,c,a, ab,bc,ca, abc, bca, abca. Sorted ones: a,b,c,a, ab, bc? bc: b<=c yes, so bc sorted. Actually bc is indices1-2, yes. Also abc? a<=b<=c yes. So that's more: Let's list: substrings: indices: (0) a, (1) b, (2) c, (3) a; length2: (0-1) ab, (1-2) bc, (2-3) ca; length3: (0-2) abc, (1-3) bca; length4: (0-3) abca. Sorted condition: a (yes), b (yes), c (yes), a (yes); ab (yes), bc (yes), ca: c > a? no, so not; abc (yes), bca: b<=c? yes, c>a? no (c>a), so not; abca: a<=b, b<=c, c>a, so not. So sorted count: a,b,c,a,ab,bc,abc = 7. That's exactly sum runs: run1 length3 => 6, run2 length1 => 1 total 7. So correct.
Thus method holds.
Now, consider large N: straightforward.
Thus solution is simple.
We should also note: The input may have whitespace after string? Using split() takes care.
Now, final code.
But wait: The problem statement says "First line of each test case contains N - length of string . Second line contains S - the given string." So there is a newline after N and then S. So using split works.
Edge: N may be 0? Not according to constraints.
Now, we should think about potential pitfalls: When reading with split, if the string S contains spaces (it won't), it would be broken. But it's all lower case letters.
Now, is there any scenario where the run length could be huge causing integer overflow in Python? No, Python can handle.
Thus final.
Now, the answer: Implementation.
I'll provide the code in Python.
Now, might there be a requirement to handle multiple test cases and use fast I/O? I'll include.
Thus final answer.
Now, I'll produce final message: explanation and code.
But the instruction: "Write a complete solution in python." So I need to provide the code.
But as ChatGPT, I should respond with final answer: include explanation? Usually we output just the code? The prompt: "Roy has a string S..." It's a problem description. We are to provide solution. In typical interaction, we output the code. But may also include explanation. I'll provide both? The instructions: "Write a complete solution in python." So I can give a solution with explanation. But maybe they just want code. I'll provide a well-commented code.
Given it's a typical competitive programming answer, I'll output a code block.
Thus final answer. ```python
import sys
def count_sorted_substrings(s: str) -> int:
"""
Returns the number of substrings of s that are non-decreasing
(sorted lexicographically).
"""
total = 0
run_len = 1 # length of current non-decreasing run
n = len(s)
for i in range(1, n):
if s[i] >= s[i-1]:
run_len += 1
else:
# add all substrings of the completed run
total += run_len * (run_len + 1) // 2
run_len = 1
# add the last run
total += run_len * (run_len + 1) // 2
return total
def main() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it)) # length, not needed explicitly
s = next(it).decode() # the string itself
out_lines.append(str(count_sorted_substrings(s)))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()