We need to solve: Given two strings s and c (both uppercase letters). We can perform at most one swap of two distinct indices in s (or possibly zero swaps). The resulting string s' must be strictly lexicographically smaller than c. If possible, output any such s'. Otherwise output "---". Constraints: total length of s across test cases ≤5000, total length of c ≤5000, so O(n^2) per test case might be okay for each string individually? But |s| up to 5000 per test case, O(n^2) could be 25 million worst-case, but total sum of |s| is 5000, so worst-case per test could be 5000 length, one test only; O(n^2) = 25e6, which is fine. So we can afford O(|s|^2) per test? But careful: sum of lengths is small, but each test could be 5000, that's okay.
But we need to be careful: we need to find any swap (or no swap) that yields s' < c.
Observation: We want s' as small lexicographically as possible? Not necessarily smallest, just any that is < c. But to find one, we can try to construct optimal swap? Or try to find lexicographically smallest string reachable with at most one swap; then compare with c. But that could be O(n^2) to compute the minimal after one swap. Since total length sum small, we can just simulate all possible swaps? Number of possible swaps is O(n^2), but n up to 5000 gives ~12.5 million, which may be borderline but okay in C++? Python might be heavy but still doable if optimized? The problem might be intended for C++ but we can try to design an algorithm O(n) or O(n log n). Let's think.
Better approach: Since we only need to find any s' < c, we can try to greedily make s smaller lexicographically at the earliest possible position.
Consider we can swap two characters. The effect is: we take two positions i < j, swap s[i] and s[j]. The lexicographic order changes at the first position where they differ from original. But to make s' smaller than c, we don't necessarily need the minimal possible string; we just need to be less than c.
We can consider comparing s and c without swap. If s < c already, we can output s (no swap) or any swap still < c? But careful: The problem says "swap no more than two letters", meaning we can also not swap. So if s < c, answer is s. Wait: but they said "swap no more than one pair" (i.e., at most one swap). So zero swaps is allowed. So if s < c, we can output s. In example 3, they output "APPLE" (no swap). So that's valid.
Otherwise, s >= c lexicographically. Actually we need strictly smaller, so if s == c, not allowed. So if s < c, trivial.
Now if s >= c, we need to see if we can make s' < c with at most one swap.
We need to find some swap such that the resulting string is lexicographically smaller than c.
We can think: after swap, the new string can be different. We want to achieve s' < c. We can approach by scanning from left, and find the first position where s' and c differ, and ensure that at that position, s'[i] < c[i].
We can treat the swap as: we can bring a smaller character from later to an earlier position, or a larger character to later position. The typical approach to minimize lexicographically with one swap is: find the smallest character in the string that appears after the first position, and swap it with the first character if it's smaller; else continue. But we need not minimal; we need just < c.
Better: We'll try to construct a candidate s' that is < c. Let's attempt to simulate the lexicographic comparison between s' and c.
Let n = |s|, m = |c|. Actually s and c lengths may differ. Lexicographic comparison: compare character by character until min(n,m). If all equal up to min, then the shorter is smaller if it is a proper prefix. So we can also potentially make s' shorter? No, swapping doesn't change length, so we cannot change length. So if |s| < |c| and s equals c prefix, then s < c already; that would have been caught by s < c. But if s < c by length, we are done. So we only worry when s >= c, which means either s > c by character or s == c (equal up to min, but lengths: if |s| == |c| and s == c, then not <; if |s| > |c|, and s has prefix c, then s > c because longer after equal prefix). So we need to consider length differences.
Given that we can only swap, we cannot change length. So if |s| > |c| and s's prefix matches c exactly, then s > c always? Actually if |s| > |c|, and s[0...|c|-1] == c, then s > c because s is longer and c is a prefix, so s > c (since a proper prefix is smaller). So to make s' < c, we need to break that prefix at some position within min(n,m) such that s'[i] < c[i] while earlier positions match c. Or we could make s' a proper prefix of c? That would require shortening s, not possible. So we must have at least one position i where s'[i] < c[i] and for all j < i, s'[j] == c[j].
If we cannot achieve that, impossible.
Thus, we need to find indices i<j such that after swapping, the prefix matches c up to i-1, and at position i we have s'[i] < c[i].
We also could consider zero swaps if s < c already. So now handle case s >= c.
We can attempt to find the smallest lexicographically achievable string via at most one swap, call it best. If best < c, we output best; else maybe there is some non-minimal but still < c? Could there be a case where minimal string after one swap is >= c, but some other swap yields s' < c? That seems possible if the minimal is too small? Actually if minimal after one swap is still >= c, then any other swap yields a string that is lexicographically >= minimal? Not necessarily: minimal is the smallest possible; all other swaps produce strings that are >= minimal (since minimal is smallest). So if minimal >= c, then all strings >= minimal >= c, so no swap yields < c. So checking minimal after one swap suffices to determine if any swap can yield < c, because if minimal < c, then answer exists (and minimal itself is a valid answer, unless minimal equals c? But it would be < c). But careful: minimal after one swap could be equal to c? That is not < c. But then maybe another swap yields < c? No, if minimal is equal to c, any other string is >= minimal = c, so >= c. Could any be less? Only if there is a string less than minimal, contradiction. So minimal is the lower bound. So yes, we can compute the lexicographically smallest string obtainable by at most one swap. If that string < c, we output that (or any that is < c). If it >= c, then impossible.
But is this correct for the case where we can also do zero swaps? That's included because zero swaps yields s. So the minimal among all strings from {s} union {strings from one swap} is the minimal after at most one swap. So we compute min over all possibilities. If that min < c, then answer exists (and that min is valid). If that min >= c, then no valid.
But is it always optimal to output the minimal? It is allowed to output any. So yes.
So we can just compute the minimal string after at most one swap. That is a known problem: given a string, you can swap at most one pair of characters, find the lexicographically smallest string possible. Approach: Greedy: For each position i from 0 to n-1, we look for the smallest character that appears later (including possibly equal?), and if there is a character smaller than s[i], we swap with the rightmost occurrence? Actually careful: to get the smallest overall, we want to swap the earliest possible position with the smallest possible character from later. But we need to ensure we pick the right character. Typical solution: For each i from 0 to n-1, find the minimum character in suffix i+1 onward. If that min is < s[i], then we swap s[i] with the rightmost occurrence of that min (because swapping with the rightmost may produce a smaller result? Let's think: For lexicographically smallest, we want to make the earliest possible position as small as possible. So we scan from left, find the first position i where there exists a character in the suffix that is smaller than s[i]. Then we want to swap s[i] with the smallest character from the suffix. If there are multiple occurrences of that smallest character, which one to swap? Since swapping with a later index does not affect prefix up to i, but the character at i becomes the smallest. However, after swapping, the character that moves to the later position could affect the string after i. To minimize the overall string, we should swap with the rightmost occurrence of that smallest character, because that will put the largest possible character into the later position (since the character we swap out from i is presumably larger than that min, but among positions with the min, the later we swap, the less effect on the suffix? Actually, suppose we have s[i]=X, and min suffix = Y (< X). We want to put Y at i. For the suffix, we will replace some position j (with s[j]=Y) with X. We want the resulting suffix after i to be as small as possible. Since we already fixed position i to Y, the suffix should be minimized as well. Swapping with the rightmost occurrence of Y means we put X at the rightmost possible position, which might be less harmful because later positions matter less lexicographically? Actually, lexicographic order: after position i, we compare the next characters. To minimize the overall string, we want the suffix after i to be as small as possible. So we want the character placed at the swapped position (j) to be as small as possible, and also the rest of the suffix unchanged except at j. Since we swap s[i] and s[j], the suffix after i (excluding i) will be the original suffix with one character changed: at position j, we put X. So we want the modified suffix to be lexicographically minimal. Among all j where s[j] = Y, we should choose the one that yields the smallest possible suffix after i. That typically means we want to put X at the position that results in the smallest possible string after i. Since the suffix apart from j stays the same, we want the first index where the suffix differs from the original to be as small as possible? Actually, we compare suffixes starting just after i. The swapped string from i+1 onward: positions i+1...j-1 are unchanged; position j becomes X; positions after j unchanged. Since X is larger than Y? Actually X > Y. So placing X at an earlier j will cause at that earlier position a larger character, making the suffix larger. Placing X at a later j means the suffix up to that later point remains small (as original) and only later gets larger, which has less impact because lexicographic comparison stops at the first difference. So to minimize the suffix, we want to delay the larger character as far right as possible, i.e., swap with the rightmost occurrence of Y. This is classic.
Thus algorithm to compute minimal after one swap: For i from 0 to n-1, find the smallest character in s[i+1:]; if it is < s[i], then find the rightmost index where this smallest occurs (from the end), swap s[i] with that character, and break. If no such i, then s is already minimal (i.e., non-decreasing? Actually it's already the smallest permutation with one swap? No, if string is like "BAB": at i=0, min suffix is 'A' < 'B', swap with rightmost 'A' at index 2 yields "ABB". That is minimal. So algorithm yields minimal with one swap. But note that we could also choose to not swap if s is already minimal? But we consider at most one swap, so if s itself is smaller than any swap, then minimal is s itself. Our algorithm can compute min by checking if any swap yields a smaller string; if none, then minimal is s.
But careful: The algorithm described (swap at first i where suffix min < s[i] with rightmost min) indeed yields the lexicographically smallest possible string achievable with exactly one swap. But is it possible that doing no swap yields a lexicographically smaller string than that? No, because if there is a swap that yields a smaller string than s, then minimal is that; if none, then s is minimal. So we can compute minimal as: attempt to find the first i where there exists a smaller character later; if found, perform the swap (rightmost min) to get candidate; else minimal = s.
But note: The algorithm yields the smallest string with exactly one swap. But what about the possibility of not swapping? That's s, which is considered in the set "at most one swap". So the minimal among all possibilities is the smaller of s and the one-swap result. But if a swap yields a string that is smaller than s, then it becomes the minimal; if not, s remains minimal. So we can compute candidate = s, and if we can find a swap that yields a string < candidate, we update to that. But the above algorithm gives the smallest possible via exactly one swap; we can compare with s to pick the minimum.
But there is nuance: Could there be a case where making a swap yields a string that is lexicographically smaller than s but not necessarily the smallest possible, but still < c, while the smallest possible (from a swap) might be < c as well, but maybe the smallest possible is also < c, so it's fine. But if the smallest possible is >= c, but there exists some other swap that yields a string < c? As argued, no because smallest is the lower bound. So we can just compute the minimal.
Thus the problem reduces to: Compute min_string = the lexicographically smallest string achievable from s by at most one swap. If min_string < c, output min_string; else output "---".
Check with examples:
-
s="AZAMON", c="APPLE". Compute minimal: scan i=0: s[0]='A', min suffix = ? suffix from 1: Z,A,M,O,N. The smallest is 'A' (equal). Since we need strictly smaller to improve? Actually we need a character < s[i] to swap. At i=0, min is 'A' which is not < 'A'. So no. i=1: s[1]='Z', suffix from 2: A,M,O,N. Smallest = 'A' < 'Z'. So swap with rightmost occurrence of 'A'? In suffix, 'A' appears at index 2? Actually s indices:0 A,1 Z,2 A,3 M,4 O,5 N. Rightmost 'A' is at index 2? Actually after index 1, the positions 2,3,4,5: there is 'A' at index 2 only; 'N'? No, so rightmost is index 2. Swap indices 1 and 2 yields "AAZMON"? That's not "AMAZON". Wait "AAZMON" is lexicographically "AAZMON". But "AMAZON" is smaller? Compare "AAZMON" vs "AMAZON": At index 0 both 'A', index1: 'A' vs 'M', 'A' < 'M', so "AAZMON" is actually smaller than "AMAZON". So "AAZMON" < "AMAZON". But the answer they gave is "AMAZON". So "AAZMON" is also < "APPLE"? Let's check: "AAZMON" vs "APPLE": index0 'A' vs 'A', index1 'A' vs 'P', 'A' < 'P', so yes, "AAZMON" < "APPLE". So why did they output "AMAZON"? Because any answer is acceptable. So minimal string after one swap for "AZAMON" is "AAZMON"? Let's verify: Is there any swap that yields an even smaller string? Swap indices 1 and 2 gives "AAZMON". Swap indices 1 and 5 gives 'Z' with 'N'? That yields "ANA MOZ"? Actually swap 1 and 5: s[1]='Z', s[5]='N' -> "ANAMOZ"? Wait: 0 A,1 Z->N,2 A,3 M,4 O,5 N->Z => "ANA MOZ"? Actually string: index0 A, index1 N, index2 A, index3 M, index4 O, index5 Z => "ANAMOZ". Compare "AAZMON" vs "ANAMOZ": at index0 both 'A', index1: 'A' vs 'N', 'A' < 'N', so "AAZMON" is smaller. Swap indices 0 and something? At i=0, no smaller char. So minimal is indeed "AAZMON". But the answer they gave is "AMAZON". So any valid string works. So minimal is valid. So algorithm would output "AAZMON", which is acceptable. But we must confirm that minimal < c? "AAZMON" < "APPLE" => true. So output would be "AAZMON". Acceptable.
-
s="AZAMON", c="AAAAAAAAAALIBABA"? Actually example: second test case: "AZAMON AAAAAAAAAAALIBABA". s="AZAMON", c="AAAAAAAAAAALIBABA"? Wait the input: "AZAMON AAAAAAAAAAALIBABA". Possibly many As. Compute minimal string from s: "AAZMON". Compare with c: c begins with many As. "AAZMON" vs "AAAAAAAAAAALIBABA": At index0 'A' = 'A'; index1 'A' = 'A'; index2 'Z' vs 'A'? Actually c's third character? Let's assume c: "AAAAAAAAAAALIBABA". It starts with many As. The length of c is maybe longer? But we compare lexicographically: We compare character by character. The minimal s after swap is "AAZMON". Since c has many As, compare: s: A A Z... ; c: A A A... ; at index2, 'Z' > 'A', so s > c. Actually 'Z' > 'A', so "AAZMON" > c. So minimal >= c? Actually it's > c. So no swap yields < c? Check if s itself < c? s = "AZAMON". Compare: index0 A=A; index1 Z vs A? Z > A, so s > c. So minimal = "AAZMON" which is > c, so answer impossible. Output "---". That matches.
-
s="APPLE", c="BANANA". s < c? Compare: A < B, so s < c, answer s. So algorithm works.
Thus approach: For each test case:
- If s < c: print s.
- Else: compute best = minimal string after at most one swap. If best < c: print best; else print "---".
Now need to ensure correctness: Could there be a case where s >= c, minimal after one swap is >= c, but some non-minimal swap yields < c? Let's attempt to find a counterexample. Suppose s = "BBD", c = "BBC". s >= c? Compare: B B D vs B B C: At index2: D > C, so s > c. Minimal after one swap: we can swap to get smaller strings. Possible swaps: Swap positions 0-1: "BBD" same; 0-2: "DBB" (D B B) which is larger? Actually "DBB" vs original: D... larger; 1-2: "BDB". Find smallest: Try algorithm: i=0: s[0]='B', min suffix = from index1: 'B','D' => min='B' not < 'B'. i=1: s[1]='B', suffix min from index2: 'D' > 'B'? Actually 'D' > 'B', so not smaller. So no swap yields a smaller string. So minimal = s = "BBD". That's > c. But could we swap to get "BDB"? Compare "BDB" with c="BBC": index0 B=B, index1 D vs B => D > B, so > c. Swap 0-2 gives "DBB": D > B at index0, so > c. So no swap yields < c. So impossible. That matches.
But consider case where minimal after one swap is > c, but some other swap gives < c? Since minimal is the smallest among all possibilities, if minimal > c then all > c. So no.
What about case where minimal after one swap equals c? Then no < c. So fine.
Thus solution is sound.
Now we need to implement efficiently for total length ≤5000. Computing minimal after one swap can be done in O(n^2) by trying all swaps, but better O(n) or O(n log n) using precomputed min suffix and rightmost occurrences. Since total length 5000, O(n^2) is fine, but to be safe in Python, we can implement O(n^2) as worst-case 25 million operations per test? Actually if one test has n=5000, then number of swaps = n*(n-1)/2 ≈ 12.5 million. For each swap we'd need to construct new string? That would be O(n) per swap, too heavy. So we need more efficient.
But we can compute minimal without brute force. The known approach is O(n) using suffix min and last occurrence.
Let's design algorithm to compute minimal after at most one swap:
Given string s (list of chars). We'll compute:
- If s is already the smallest possible via one swap? Actually we need to find the lexicographically smallest string achievable by at most one swap.
Standard method: For each index i from 0 to n-1, we want to see if we can improve by swapping with a later character that is smaller than s[i]. Among all such swaps, the one that yields the smallest string is to swap at the earliest i where such smaller character exists, and then with the smallest possible character (the minimum in suffix) and among those, the rightmost occurrence. But is that always optimal? Yes, because we want the earliest position to be as small as possible. So the algorithm:
- Preprocess from right to left: For each position i, compute the minimum character in s[i+1:], and also for each character, maybe the rightmost index where that minimum occurs? Actually we need the minimum character value. But we also need to know the rightmost index where that minimum occurs. Because after we find i where min_suffix[i] < s[i], we swap s[i] with the rightmost occurrence of that min character in the suffix (i+1..n-1). That yields the minimal string.
But is it possible that swapping at a later i with a smaller character (not necessarily the first i) could produce a string that is even smaller than swapping at the first i? Let's test: Suppose s = "B C A A"? Actually we need to consider that the first i where suffix min < s[i] gives the earliest position we can lower. Any swap that doesn't lower the earliest possible position (i.e., leaves earlier positions unchanged) will result in a string that is lexicographically larger than one that lowers an earlier position. Because lexicographic order is dominated by the first differing character. So the minimal possible string will have the smallest possible character at the earliest index where we can change it. Thus the first index where we can reduce (by swapping with a smaller character) is the optimal spot to swap. But is there a case where we might want to not swap at the first reducible index because swapping there would cause the suffix to become larger in a way that overall string ends up larger than if we swapped at a later index? For example, consider s = "ABBA". i=0: s[0]='A', suffix min = from index1: B, B, A? Actually suffix: B, B, A => min = 'A' which is not less than 'A'? Actually 'A' == 'A', so not less. So i=0 can't reduce. i=1: s[1]='B', suffix min from index2: B, A => min='A' < 'B', so first reducible index is 1. Swap s[1] with rightmost 'A' at index 3 yields "A A B B"? Actually swap indices 1 and 3: s becomes "A A B B"? Wait original: indices 0 A,1 B,2 B,3 A -> after swap 1 and 3: 0 A,1 A,2 B,3 B -> "AABB". That is the result. Could there be a swap at later index that yields a smaller string? Swap indices 2 and 3: "ABAB"? Compare "AABB" vs "ABAB": at index0 both A; index1: A vs B => A < B, so "AABB" is smaller. So indeed first reducible yields smallest.
But what about s where at first reducible index, the min character is the same as some later min but swapping with it might cause the suffix to become large, but perhaps swapping at a later index could yield a smaller string? For lexicographic order, if we lower the character at index i, the resulting string will be smaller than any string that leaves the prefix up to i-1 same but has a larger character at i. So any string that doesn't change the prefix up to i-1 and has a character at i larger than the minimal achievable at i will be larger. Since we can achieve at i the smallest possible character (the min of the suffix). So swapping at the first reducible index with the smallest possible character yields the minimal possible string among all swaps. Even if later we might achieve a smaller suffix, the earlier character dominates.
However, there is a subtlety: What if we can lower the character at index i but doing so also changes an earlier character? No, swapping i with j>i only changes positions i and j. So prefix up to i-1 remains unchanged. So if we can make s'[i] smaller than s[i] (by swapping with a smaller char), then s' will be lexicographically smaller than any string that keeps s[i] unchanged (or makes it larger). So to minimize, we want the earliest i where we can decrease s[i]. But what if we cannot decrease any character? That means s is non-decreasing? Actually not exactly: we might be able to swap but not decrease any position: e.g., s = "BA". i=0: s[0]='B', suffix min = 'A' < 'B', so we can decrease. So we can always decrease if there is any inversion (a larger character before a smaller one). If s is already sorted non-decreasing, then no swap can decrease the lexicographic order (any swap would either increase or keep same? Actually swapping in a non-decreasing string might create an inversion at some later point but could increase earlier position? e.g., "AAAB" -> swap first A with last B yields "BAAA", which is larger because B > A at first index. So indeed cannot make it smaller. So minimal is original s.
Thus algorithm: Find the earliest index i such that there exists j>i with s[j] < s[i]. If none, minimal = s. Else, let min_char = min(s[i+1:]). Then find the rightmost index j where s[j] == min_char and j>i. Swap s[i] and s[j] to obtain candidate. That candidate is the minimal string achievable by at most one swap.
But is it possible that performing no swap yields a string smaller than this candidate? No, because we already determined that there exists a swap that yields a smaller string than s (since we found a position where we can decrease). So candidate < s. So minimal is candidate.
Thus algorithm is O(n) to compute suffix min and rightmost occurrence of the min at each step? Actually we can compute suffix minimum array: min_suffix[i] = minimum character in s[i:], but we need for i (the position from which we consider swapping) the minimum in suffix starting at i+1. So we can compute an array min_from[i] = minimum character in s[i:] maybe. Then for i, min_char = min_from[i+1] if i+1 < n. But we also need the rightmost occurrence of that min_char in the suffix. So we can precompute for each position the rightmost index where the min occurs? But that's tricky: For each i, the min_char might be different. Instead we can: iterate i from 0 to n-1, maintain a data structure of characters to the right? But since n ≤ 5000, we can for each i, scan from right to find the min and its rightmost index in O(n) per i, leading to O(n^2). That is acceptable given total n sum 5000 => up to 25 million operations, which is fine in Python if done carefully with lists and not constructing strings each time. But we can also do O(n) total.
Given the small constraints, I'd implement O(n^2) straightforwardly: For each i from 0 to n-2, find the minimum character in s[i+1:] and its rightmost index. If that min_char < s[i], then swap and break. This is O(n^2) but with n up to 5000, worst-case n^2=25e6, plus overhead for each test case, which is okay in Python (maybe around 0.1-0.2 seconds? Possibly a bit more but still within typical time limits (2 secs) since total sum of n is 5000, only one test might be 5000. 25 million simple operations is fine). But we need to be careful: For each i, scanning from i+1 to end to find min and rightmost index is O(n). That's 25 million comparisons, okay.
Alternatively, we could precompute suffix mins and last occurrence arrays. Let's design O(n):
- Compute array min_from[i] = minimum character in s[i:] (inclusive). And also pos_min[i] = the rightmost index >= i where s[pos] equals min_from[i]? But we need for each i the minimum in suffix i+1, which is min_from[i+1]. However, if we know min_char = min_from[i+1], then we need the rightmost occurrence of min_char in s[i+1:]. That could be precomputed by scanning from right and for each character store its last occurrence. But the minimum char can change as i changes. So we could store for each position, the rightmost index of each character? That's 26 possibilities, which is constant. We can precompute for each position i (from n-1 downto 0) an array last[char] indicating the last occurrence index of that character from i to n-1. Then for each i, we can query the min char in s[i+1:] by looking at the global minimum? Actually we need to find the min character in the suffix. But we can compute suffix_min_char[i] = minimum character from i to n-1. Then for each i, the min_char = suffix_min_char[i+1] (if i+1<n). Then we need the rightmost index of that min_char in s[i+1:]. That can be obtained from a precomputed array that for each position i (starting index) and each character, the last occurrence? But we can also compute an array rightmost_of_min_from[i] = the rightmost index where the minimum character from i onward occurs. That can be computed from right to left: maintain current min and its rightmost index. But for each i, the min in suffix i+1 may be different from min in suffix i. However, we can compute an array suffix_min_char[i] and suffix_min_pos[i] (rightmost index of that min) for each i. Let's define for index i (0-based) we compute min_char[i] = minimum character in s[i:], and min_pos[i] = the largest index j >= i such that s[j] == min_char[i]. This can be computed in one pass from right to left: start at n-1: min_char[n-1] = s[n-1], min_pos[n-1]=n-1. For i from n-2 downto 0: if s[i] < min_char[i+1], then min_char[i]=s[i], min_pos[i]=i; else if s[i] > min_char[i+1], then min_char[i]=min_char[i+1], min_pos[i]=min_pos[i+1]; else (s[i]==min_char[i+1]), then min_char[i]=s[i], min_pos[i]=i (or keep min_pos[i+1]? Actually we want the rightmost occurrence of the minimum. Since s[i] equals the minimum, and i is left of min_pos[i+1], the rightmost occurrence is still min_pos[i+1] because it's further right. So we should set min_pos[i]=min_pos[i+1] to keep the rightmost. So condition: if s[i] < min_char[i+1] -> new min, min_pos[i]=i; if s[i] > min_char[i+1] -> keep, min_pos[i]=min_pos[i+1]; if s[i] == min_char[i+1] -> same min, but rightmost is still min_pos[i+1] (since it's further right), so min_pos[i]=min_pos[i+1]. So we can compute.
Then for each i, the minimum character in s[i+1:] is min_char[i+1] (if i+1 < n). And the rightmost index where that min occurs in s[i+1:] is min_pos[i+1] (since min_pos[i+1] is the rightmost index of the min in that suffix). However, careful: min_pos[i+1] gives the rightmost index >= i+1 where s[index] equals min_char[i+1]. Yes, that's exactly what we need. So we can just iterate i from 0 to n-2, check if min_char[i+1] < s[i]. If yes, then swap s[i] and s[min_pos[i+1]] to get candidate string. That yields the minimal after one swap.
Edge case: Could there be a scenario where we can swap two characters that are both before some index? But our method only considers swapping with a later character that is smaller. That covers all swaps that could decrease the lexicographic order? What about swapping two characters where the smaller is earlier and the larger is later? That would increase lexicographic order (since we would put larger character earlier). So that would not make the string smaller. So any swap that yields a smaller string must involve moving a smaller character from a later position to an earlier position. Indeed, if we swap s[i] and s[j] with i<j, the new character at i becomes s[j]. For the string to become smaller, we need s[j] < s[i]. So the swap must be of that form. So our search for i where exists j>i with s[j] < s[i] covers all possibilities. So algorithm is correct.
Thus we can compute minimal in O(n).
Implementation steps:
For each test case:
-
read s and c as strings.
-
if s < c: print(s); continue
-
else:
n = len(s)
convert s to list of chars for mutability.
Compute arrays min_char and min_pos of length n (or n+1 sentinel).
Initialize min_char[n-1] = s[n-1], min_pos[n-1] = n-1
for i from n-2 down to 0:
if s[i] < min_char[i+1]:
min_char[i] = s[i]; min_pos[i] = i
elif s[i] > min_char[i+1]:
min_char[i] = min_char[i+1]; min_pos[i] = min_pos[i+1]
else: # equal
min_char[i] = s[i]; min_pos[i] = min_pos[i+1] # keep rightmost
Now, iterate i from 0 to n-2:
if min_char[i+1] < s[i]:
j = min_pos[i+1]
# swap s[i] and s[j]
s_list = list(s) # since we need to produce a string, we can copy original.
s_list[i], s_list[j] = s_list[j], s_list[i]
candidate = ''.join(s_list)
if candidate < c:
print(candidate)
break
else:
# candidate is not < c? But candidate is the minimal after one swap. If it's not < c, then impossible? Actually if candidate is not < c, then no swap yields < c, because candidate is the minimal possible after one swap (and s >= c already). But we need to be sure that candidate is indeed the minimal among all one-swap possibilities. But we derived that this candidate is the minimal overall after at most one swap (since s >= c, s is not < c, so we consider swap). However, what if candidate is >= c but there exists some other swap that yields a string < c? As argued, impossible because candidate is minimal. So we can output "---". But careful: Could there be a scenario where the minimal candidate is >= c, but the original s (which is >= c) might be < c? No, s is not < c because we are in else branch. So it's impossible.
So we can directly output "---" after the loop if no such i found that yields candidate < c? Actually we should check: if we found i where min_char[i+1] < s[i], we produce candidate. Then if candidate < c, we output and done. Else, we should output "---". But wait: Could it be that we found such i, but candidate is not < c, yet there might be a different swap (not the minimal one) that yields a string < c? That would mean minimal candidate >= c but some other swap yields a string smaller than c? But minimal candidate is the smallest among all swaps, so if it's not < c, then all swaps >= candidate >= c (since candidate is min). So none < c. So output "---". Good.
But what if we never find any i such that min_char[i+1] < s[i]? That means s is already non-decreasing? Actually it means there's no inversion where a later character is smaller. Then no swap can produce a lexicographically smaller string than s. So minimal = s. Since s >= c (we are in else), and s is not < c, we need to check if s < c? Already not. So output "---".
Thus algorithm:
if s < c: print(s); continue.
else:
compute suffix min and rightmost as above.
found = False
for i in range(n-1):
if min_char[i+1] < s[i]:
j = min_pos[i+1]
s_list = list(s)
s_list[i], s_list[j] = s_list[j], s_list[i]
candidate = ''.join(s_list)
if candidate < c:
print(candidate)
found = True
break
if not found:
print("---")
But is there a case where s >= c, but s itself is not < c, but we might not need to swap because s could be equal to c? Not allowed. So we need to swap.
Now consider a nuance: Could it be that s >= c, but the minimal string after swap is < c, but the swap we produce using the first i with min_char[i+1] < s[i] yields a candidate that is indeed minimal, but what if this candidate is < c? Then we output it. Good.
But is it guaranteed that candidate is the minimal? Let's test with some edge cases.
Consider s = "CBAD". This string: indices 0:C,1:B,2:A,3:D. Compute suffix min: from right: i=3: min='D', pos=3. i=2: s[2]='A' < min_char[3]='D'? 'A' < 'D', so min_char[2]='A', pos=2. i=1: s[1]='B', min_char[2]='A' -> 'B' > 'A', so min_char[1]='A', pos=2. i=0: s[0]='C', min_char[1]='A' -> 'C' > 'A', so min_char[0]='A', pos=2.
Now iterate i:
i=0: min_char[1] = min_char[1] = 'A' (since i+1=1), compare s[0]='C', 'A' < 'C' -> true. j = min_pos[1] = 2. Swap indices 0 and 2 -> s becomes "ABCD"? Actually swap 0 and 2: C <-> A gives "AB C D"? Let's list: s[0]=C, s[2]=A -> after swap: index0=A,1=B,2=C,3=D => "ABCD". That's the result. Is this the minimal? Possibly yes. Could there be a swap yielding a smaller string? Swap 0 and 1 yields "BCAD"? Compare "ABCD" vs "BCAD": A < B, so "ABCD" is smaller. Swap 0 and 3 yields "DBAC"? D > A, larger. So minimal is "ABCD". Good.
Now consider s = "BAB". Indices 0:B,1:A,2:B. Compute suffix: i=2: min='B', pos=2. i=1: s[1]='A' < min_char[2]='B' -> new min_char[1]='A', pos=1. i=0: s[0]='B' > min_char[1]='A' -> min_char[0]='A', pos=1.
Iterate i: i=0: min_char[1]='A' < s[0]='B'? yes. j = min_pos[1]=1. Swap indices 0 and 1 => "ABB". That's minimal. Good.
Consider s = "AAB". Actually no inversion? s[0]=A, min_char[1]? Compute: i=0: min_char[1] = min of suffix from 1: A,B? min='A' (equal), not < so skip. i=1: min_char[2] = B? s[1]=A, B > A? Actually B > A, so min_char[2]='B', compare s[1]='A', not <. So no swap. Minimal is original "AAB". Good.
Now consider s = "ABCA". Indices 0:A,1:B,2:C,3:A. Suffix: i=3: min='A', pos=3. i=2: s[2]='C' > min_char[3]='A' -> min_char[2]='A', pos=3. i=1: s[1]='B' > min_char[2]='A' -> min_char[1]='A', pos=3. i=0: s[0]='A' == min_char[1]='A'? So min_char[0]='A', pos=min_pos[1]=3 (since equal, keep rightmost). Now iterate i: i=0: min_char[1]='A' < s[0]='A'? no. i=1: min_char[2]='A' < s[1]='B'? yes. j = min_pos[2]=3. Swap indices 1 and 3 => s becomes "A A C B"? Actually swap 1 and 3: index1 becomes A, index3 becomes B => "AACB". That's candidate. Could there be a swap that yields a smaller string? Swap 0 and 3: "C B A A"? Actually swap 0 and 3: "CBA A"? Let's see: indices 0 and 3 swap: 0:A<->A? Actually s[3] is A, so swap yields "ABCA"? No, same. Swap 0 and 3 gives "ABCA"? Actually original: [A,B,C,A] swap 0 and 3 -> [A,B,C,A] because both A, same. Swap 2 and 3: [A,B,A,C] => "ABAC". Compare "AACB" vs "ABAC": at index0 A, index1 A vs B => 'A' < 'B', so "AACB" is smaller. So minimal likely "AACB". But is there "AABC"? No, cannot. So candidate "AACB" is minimal. Good.
Now consider s = "DAB". indices 0:D,1:A,2:B. Suffix: i=2: min='B', pos=2. i=1: s[1]='A' < min_char[2]='B' -> min_char[1]='A', pos=1. i=0: s[0]='D' > min_char[1]='A' -> min_char[0]='A', pos=1. Iterate i=0: min_char[1]='A' < s[0]='D', swap 0 and 1 => "ADB". That yields "ADB". Could there be a smaller? swap 0 and 2 => "BAD" (B vs A? Compare "ADB" vs "BAD": 'A' < 'B', so "ADB" is smaller. So minimal is "ADB". Good.
Now consider a case where there are multiple equal minimum characters. The algorithm picks rightmost. That yields minimal suffix as reasoned.
Thus algorithm is correct.
Now we need to also consider the case where we might have a swap that yields a string that is < c, but the minimal string after swap is not < c, but some other swap yields a string < c? That would mean minimal after swap is >= c, but some other string after swap is < c. But since minimal is the smallest, if minimal >= c, then all others are >= minimal >= c, so not < c. So impossible.
Thus approach works.
But let's test some edge cases:
-
s and c lengths differ. The lexicographic comparison works as usual.
-
s may be longer than c, and s may be less than c if s is a prefix? Actually if s is prefix of c and |s| < |c|, then s < c. So caught by s < c.
-
If s is longer than c, and s's prefix equals c, then s > c. Then we need to see if we can make s' < c. That would require altering the prefix up to the length of c, because after making a change within the first |c| characters, we might get s'[i] < c[i] for some i < |c|, or if we make change only after |c|, the prefix remains equal to c, and because s' is longer, it would still be > c (since proper prefix rule: if strings are equal up to min length, the shorter is smaller). So we must ensure that after swap, the string's prefix up to min(len(s), len(c)) becomes lexicographically smaller. If we make a swap that only affects characters beyond length c, and the prefix up to |c| remains equal to c, then s' would still be > c because it's longer. So we need to affect within the first min(n,m) characters. Our minimal swap algorithm tries to make the string as small as possible overall, which will likely affect the earliest possible position. That's good.
But consider scenario: s = "BA", c = "AB". s = "BA" < c? Compare: B > A? Actually "BA" vs "AB": index0: B vs A, B > A, so s > c. So s >= c. Compute minimal after swap: s has inversion? i=0: min_char[1]='A' < 'B', swap yields "AB". That's candidate = "AB". Compare candidate with c: "AB" vs "AB" => not <, equal. So candidate is not < c. Is there any other swap? only one swap yields "AB". So no valid answer. Output "---". That matches.
But what if s = "AB", c = "AA"? s="AB" vs c="AA": index0 A=A, index1 B > A, so s > c. Minimal after swap? Check inversion: i=0: suffix min from 1 is 'B' (>= 'A'), no; i=1: no later. So no swap can make it smaller; minimal = "AB". Compare "AB" with "AA": at index0 A=A, index1 B > A, so >. So no answer. Output "---".
Now consider s = "AAB", c = "AAA". s > c? Compare: A=A, A=A, B > A -> s > c. Minimal after swap: Check inversions? i=0: suffix min from 1 is min('A','B')='A' == s[0]; i=1: suffix min from 2 is 'B' > 'A'? Actually 'B' > 'A', so no. So no swap. s remains "AAB". "AAB" > "AAA". No answer. But could swapping the B with an A make it smaller? Swapping positions 1 and 2 yields "ABA"? Compare "ABA" vs "AAA": index0 A=A, index1 B > A, so >. Swap 0 and 2 yields "BAA"? B > A at index0, >. So no. So correct.
Now consider s = "BAA", c = "AAB". s vs c: B > A, so s > c. Minimal after swap: find inversion: i=0: suffix min from 1 is min('A','A')='A' < 'B', swap with rightmost min at index 2 => swap 0 and 2 => "AAB". candidate = "AAB". Compare with c = "AAB": equal, not <. So not valid. Could another swap produce < c? Swap 0 and 1 => "ABA": compare "ABA" vs "AAB": index0 A=A, index1 B > A, so >. So none. Output "---". But is there a possibility to get "AAA"? Not with one swap (since need two swaps). So correct.
Now consider s = "ACB", c = "ABC". s vs c: A=A, C > B, so s > c. Minimal after swap: i=0: suffix min from 1 is min('C','B')='B' < 'A'? No, 'B' > 'A'? Actually 'B' > 'A', so no. i=1: suffix min from 2 is 'B' < 'C'? Yes, 'B' < 'C'. So swap index1 with rightmost min of suffix from 2: min_char[2] = 'B', pos=2. Swap 1 and 2 => "ABC". candidate = "ABC", which equals c, not <. So no valid? But can we swap differently? Swap 0 and 2 => "BCA", which is >. So none. So answer "---". That seems correct: cannot get strictly smaller than "ABC" with one swap because the only possible string smaller than "ABC" that is reachable? Actually "ABC" is the sorted ascending; any one swap from "ACB" either gives "ABC" or "CAB" or "BAC". Among these, "ABC" is equal to c; "BAC" > "ABC"? Compare B > A at index0, so >; "CAB" >. So indeed none < c. So "---". Good.
Now consider s = "CAB", c = "BAC". s > c? Compare C > B, so s > c. Minimal after swap: i=0: suffix min from 1 is min('A','B')='A' < 'C', swap with rightmost min? min_char[1] = 'A', min_pos[1]? Let's compute: from right: i=2: min='B', pos=2; i=1: s[1]='A' < 'B' -> min='A', pos=1; i=0: s[0]='C' > 'A' -> min='A', pos=1. For i=0: min_char[1]='A', j=min_pos[1]=1. Swap 0 and 1 => "ACB". That's candidate. Compare "ACB" with "BAC": index0 A vs B, A < B, so candidate < c! So answer "ACB". That's valid. So algorithm outputs candidate < c.
Now consider s = "ABCD", c = "ABDC". s < c? Compare: A=A, B=B, C=C, D? Actually c: A B D C? Wait "ABDC": indices: 0:A,1:B,2:D,3:C. Compare s: A,B,C,D. At index2: C vs D, C < D, so s < c? Actually "ABCD" vs "ABDC": up to index1 equal; at index2: C < D, so "ABCD" < "ABDC". So s < c -> output s. Good.
Now consider s = "ABDC", c = "ABCD". s > c? Compare: A=A, B=B, D > C, so s > c. Minimal after swap: i=0: suffix min from 1 is min('B','D','C') = 'B' not < 'A'; i=1: suffix min from 2 = min('D','C')='C' < 'B'? Actually 'C' < 'B'? No 'C' > 'B'? C is larger than B (since alphabetical order). So 'C' > 'B', so no; i=2: suffix min from 3 = 'C' < 'D'? yes, 'C' < 'D', swap i=2 with rightmost min? suffix from 3: only index3='C', swap 2 and 3 => "ABCD". candidate = "ABCD". Compare with c="ABCD": equal, not <. So candidate not < c. Could another swap yield < c? Swap 1 and 3 => "ACDB"? Compare with c: A=A, C > B, so >; swap 0 and 2 => "DBAC"? >. So none. So output "---". That's correct.
Now consider s = "ZAZ", c = "AAA". s > c obviously. Minimal after swap: i=0: suffix min from 1 = min('A','Z')='A' < 'Z', swap with rightmost min? rightmost 'A' at index1? Actually suffix from 1: indices 1='A',2='Z', min='A', rightmost occurrence of 'A' is index1 (only). Swap 0 and 1 => "AZZ". candidate = "AZZ". Compare with "AAA": index0 A=A, index1 Z > A => >. So not < c. Could another swap yield smaller? Swap 0 and 2 => "ZAZ" becomes "AZZ"? Actually swap 0 and 2: "ZZA"? Let's compute: s=Z A Z, swap 0 and 2 => Z with Z? Actually both Z, so same. So only "AZZ". So no < c. So "---". But is there a possibility to get "AAZ"? No, need two swaps. So correct.
Now consider s = "BBA", c = "ABB". s vs c: B > A, so s > c. Minimal after swap: i=0: suffix min from 1 = min('B','A')='A' < 'B', swap with rightmost 'A' at index2 => swap 0 and 2 => "ABB". candidate = "ABB". Compare with c="ABB": equal, not <. Could another swap? swap 0 and 1 => "BBA" same? Actually swap 0 and 1 => "BBA" again? Wait s is "BBA": indices 0:B,1:B,2:A. Swap 0 and 1 yields "BBA" same. So only "ABB". So no < c. So output "---". That seems correct.
Now consider a scenario where the minimal string after swap is >= c, but there is another swap that yields a string < c? Suppose s = "BCA", c = "BAC". s > c? Compare: B=B, C > A, so s > c. Minimal after swap? Find i: i=0: suffix min from 1 = min('