We need to read problem: Given a string S (length up to 100k, lowercase letters), we need to find the strongest unique string that is a subsequence of S. Strongest means lexicographically greatest among all unique (all distinct characters) subsequences.
We are to output the strongest such subsequence.
Interpretation: We consider all subsequences of S that consist of distinct characters (no repeated characters). Among those, we want the lexicographically greatest. Lexicographic order: typical string comparison: compare first character, larger is greater; if equal, move next, etc. So we want a subsequence that is as large as possible? Not necessarily length; lexicographic order prioritizes earlier characters. For example, string "abvzx": Possible unique subsequences: "z", "x", "zx", "vz", "vx", "vzx", "b...", etc. Lexicographically compare: The greatest is "zx"? Let's test: Compare "zx" vs "z" -> "z" is prefix, "zx" longer so "zx" > "z". Compare "zx" vs "zv"? But "zv"? Not possible? Actually from "abvzx", we have "vzx" is possible? Let's see: characters: a,b,v,z,x. Subsequence "vzx": v then z then x -> string "vzx". Compare "zx" vs "vzx": first char: 'z' vs 'v', 'z' > 'v', so "zx" > "vzx". So indeed "zx" seems greatest. Why not "zxa"? Not possible because x is last. What about "z"? no. So "zx" is answer.
But is there any possibility that longer string can be lexicographically smaller if earlier characters are same? Actually if two strings share prefix, the longer one is greater if it continues after the shorter ends? In standard lexicographic order, if one string is a prefix of the other, the longer is considered greater (provided we treat it as usual string comparison: after comparing all characters of the shorter, if all equal, the longer is greater). So longer is beneficial only after equality on all characters of the shorter. So to maximize lexicographic order, we want the first character as large as possible. Among subsequences with that first character, we want the next character as large as possible, etc., while maintaining uniqueness (distinct characters). So this is similar to: We need to choose a subsequence (ordered as per indices) of distinct characters that is lexicographically maximal.
But careful: Since we require distinct characters, we cannot use the same character twice. However, the string S may have duplicate characters. But we only need the subsequence to have distinct characters, not that the subsequence must be a set; but it's a string, so each character is considered individually. If S contains repeated letters, we could pick at most one occurrence of that letter in the subsequence.
Goal: Find lexicographically greatest subsequence with all distinct characters.
Observation: Since lexicographic order compares from first character, the first character should be the maximum possible character we can have in any unique subsequence. But we also need to be able to have subsequent characters distinct and also following the ordering (i.e., after we pick a character at position i, we can only pick later characters from positions after i). Also we need to ensure that we can form a subsequence of distinct characters. But essentially, we can treat it as: we want to construct a string result greedily from left to right, picking the largest possible character at each step while ensuring that we can still complete the subsequence with distinct characters (i.e., after picking a character, there remains enough distinct characters later to form the rest, but we don't have a fixed length; we can stop anytime. Actually we don't need to complete to a fixed length; we can end after any number of characters. So after picking some prefix, we can always stop if no further character can be added (or if adding would not increase lexicographic order? But we want the lexicographically greatest overall, so maybe we can consider that we want to maximize the entire string. However, since we compare strings lexicographically, we want the longest possible prefix if we can make it equal on earlier characters? Actually we need to consider all possible choices. A typical approach for lexicographically maximal subsequence under constraints often uses greedy from left: at each step, we pick the largest character that allows the rest to be feasible (i.e., that we can still form a valid continuation). But here the continuation could be empty, so feasibility is always satisfied? Not exactly: because we need distinct characters overall; after picking a character c, we cannot pick c again later. But there could be other characters. So if we pick a character, we must ensure that we can still pick distinct characters for the rest, but we are not required to pick any more; we can stop. So the only feasibility condition is that after picking a character at position i, we must be able to form a subsequence of distinct characters from the remaining suffix (i.e., positions after i) that does not use any character already used. But since we can stop, we don't need to force additional characters. So the only potential infeasibility is if picking a character would make it impossible to have distinct characters later if we decide to add more? But since we are not forced to add more, the subsequence consisting of just that character is valid (unique). So at first step, we could just pick the maximum character anywhere in the string, and that would be a valid unique subsequence of length 1. But we might be able to get a longer subsequence that starts with an even larger character? Actually the maximum character available is the best first character. However, there might be a tie: if the maximum character appears multiple times, we might want to pick the earliest occurrence to leave more room for later? But later we want to maximize subsequent characters; picking a later occurrence might limit options? Typically for lexicographically maximal subsequence without uniqueness, the answer is just the entire string sorted descending? No, that's not subsequence. For typical "lexicographically largest subsequence" without constraints, you would pick from left: choose the maximum character from the whole string as first, then from the suffix after that pick the maximum as second, etc. That yields the lexicographically largest subsequence (which is essentially the decreasing sequence of maximums). But that subsequence may have repeated characters, that's allowed. However, here we require distinct characters. So we cannot repeat characters.
So we need to produce a lexicographically maximal subsequence with distinct characters. This is reminiscent of: "Find the lexicographically largest subsequence with distinct characters". This can be solved by scanning from right to left to compute the set of distinct characters available in the suffix, and then greedy from left: for each position, decide whether to take the character if it is the maximum among those that haven't been used and are still available later? But careful with lexicographic order: we want the first character as large as possible. So we should consider the maximum character that appears in S. Let's denote M = max char in S. If we take M as first character, then we can possibly add more characters after it, but they must be distinct from M and must come after the chosen occurrence. We want the lexicographically largest string. So if we pick M as first, then we need to choose the subsequent characters to form the lexicographically largest string that starts with M. But maybe there is a scenario where picking a slightly smaller first character allows a second character that is larger than any possible second character after M, making the overall string lexicographically larger? Lexicographic comparison: compare first char: M vs something smaller: M is larger, so any string starting with M will be greater than any string starting with a smaller char regardless of the rest. So we must pick the maximum possible first character. No other choice can beat that. So first character must be the maximum character present in S. But careful: What if the maximum character appears only before some other maximum? Actually it's simply the max char. So we need to pick an occurrence of the max character.
Now after picking that, we are constrained to characters after that occurrence, and we cannot use the same character again. We then want the lexicographically largest subsequence from the suffix that does not use the chosen character. That becomes a subproblem: we have suffix string (starting after the chosen index) and a set of forbidden characters (the ones already used). We want the lexicographically largest unique subsequence from that suffix without using forbidden chars. However, note: we are not forced to take any more characters; we can stop. So the optimal continuation is exactly the solution to the subproblem: given the remaining string (suffix) and set of used characters, find the lexicographically largest unique subsequence (with no repeats from used). But does the greedy approach hold? After we pick first char = M, we then solve similarly: we want the maximum possible character in the suffix that is not M? But is it always optimal to pick the maximum available character in the suffix that is not used? Let's think: we now have prefix fixed to M. We want to choose the rest to maximize the string. The rest is compared only if the prefixes are equal. So we need the lexicographically largest string from the suffix that does not use M. This is independent: we can solve recursively: from the suffix, we want the lexicographically largest unique subsequence, but with the restriction that we cannot use characters already used (just M initially). However, note that we could also decide to stop after M, which yields string "M". But perhaps adding more characters can make the string lexicographically larger because "M" as prefix of "MX" means "MX" > "M"? Since "M" is a prefix of "MX", "MX" is greater. So we always want to add as many characters as possible? Actually, if we can add any character (distinct) after M, the resulting string "M" + X will be greater than "M" because it's longer and shares prefix. So adding characters (any) increases lexicographic order. Therefore, we always want to add as many characters as possible? Not exactly; it's not about length, but any extension yields a larger string than the base if the base is a prefix. So given we have fixed prefix M, we would like to append the lexicographically largest possible string (with distinct chars not using M) from the suffix. But note: The appended string itself may be empty. If we can append any non-empty string, the result is greater. So we want to append the largest possible string (subject to constraints) if it exists. But is there any scenario where appending some characters could cause the string to become not lexicographically maximal overall? No, because any extension yields a string that starts with M and is longer, so it beats "M". However, could there be a different choice of first character (maybe not the maximum) that yields a longer string with a prefix that after some point becomes greater? But as argued, M beats any smaller first character, so we don't consider that.
Thus greedy: pick the maximum character (overall) as first. But we must also choose which occurrence to pick. Since we want to maximize the rest, we should pick the rightmost occurrence of the maximum character? Or the leftmost? Let's think: Suppose S = "abzba". Maximum char is 'z'. There are two 'z's: at index 3 (0-index? Let's say "a b z b a": indices: 0:a,1:b,2:z,3:b,4:a? Actually string "abzba": a b z b a -> indices:0 a,1 b,2 z,3 b,4 a. Also maybe another? Only one 'z'. If there were multiple, say "zaz": indices 0:z, 2:z. If we pick first 'z' at index 0, the suffix is "az". We cannot use 'z' again, so from "az", we can take 'a'? But also 'z' is forbidden. The distinct subsequence from suffix: we can take 'a' (max among allowed is 'a'), giving "za". Also could take nothing -> "z". "za" > "z". If we pick the later 'z' at index 2, suffix is empty -> result "z". So "za" is lexicographically larger than "z". So we want to pick the leftmost occurrence of maximum? Actually we need to pick an occurrence such that the suffix after it allows the largest possible continuation. Since we always want to maximize the rest, we should pick the occurrence that gives us the most freedom to have a large continuation. Usually, picking the leftmost occurrence leaves more characters after it, but also might allow more options. However, picking a later occurrence might allow more distinct characters? But generally, picking the earliest occurrence (leftmost) gives a longer suffix, which can only give a continuation that is at least as good as picking a later occurrence? Not necessarily: Because even if suffix is longer, the set of characters available in that suffix might be smaller if the earlier occurrence is before many characters that are not allowed? But they are allowed as long as distinct. But there could be a scenario: Suppose S = "z a b c ..." many characters, but after the first 'z', there are many characters, including maybe other high characters like 'y', but we can't use 'z' again. But after a later 'z', maybe there is a 'y' also? The later 'z' might have a suffix that still contains 'y', but fewer characters overall. However, since we want the lexicographically largest continuation, it's essentially the same as solving the problem on the suffix with forbidden set. If we pick an earlier occurrence, the suffix includes the later occurrence as well? Actually if there are multiple 'z's, the suffix after the first 'z' includes the later 'z' as well, but we cannot use it because 'z' is forbidden. But if we pick the later 'z', the suffix after it is shorter, but we might still be able to pick high characters that appear between the two 'z's? Those would be lost if we pick the later 'z'. So picking the earlier 'z' gives more characters to work with; it cannot be worse than picking a later one, because any continuation that is possible from a later 'z' suffix is also possible from the earlier 'z' suffix? Not exactly, because after picking the earlier 'z', we are forced to choose characters after that position, and we cannot use 'z' again. The later 'z' appears after the earlier 'z', but we cannot use it because it's forbidden. However, if we pick the later 'z', we also cannot use it in the continuation because we already used it as the first character. So both forbid 'z'. The earlier 'z' suffix includes all characters after it, including those before the later 'z' and after. The later 'z' suffix is a subset of that (specifically the suffix after the later 'z'). So any continuation from the later 'z' can also be formed from the earlier 'z' (by ignoring the part before the later 'z' and using the same subsequence after it). But careful: if we pick earlier 'z', we are allowed to pick characters from the entire suffix, including those that come before the later 'z', but we might need to ensure ordering: the subsequence after earlier 'z' must be in increasing indices. If we want to mimic the continuation that would come from picking later 'z', we could simply skip to the later 'z'? But we already picked the earlier 'z' as first character. To then pick the same continuation as from later 'z', we would need to pick characters that are after the later 'z', not before. That is possible: we can just ignore the part between earlier and later 'z' and start picking from after later 'z'. So we can produce the same continuation as from later 'z'. Therefore, the set of possible continuations after earlier 'z' is a superset of those after later 'z' (since we can always choose to skip to later). So the best continuation after earlier 'z' will be at least as good as the best after later 'z'. So picking the earliest occurrence of the maximum character yields a result that is lexicographically at least as large as picking any later occurrence. So optimal is to pick the first occurrence of the maximum character? Wait, earliest? Let's double-check: We want to maximize the whole string. First character fixed to 'z'. Then the rest is the lexicographically largest unique subsequence from the suffix after that occurrence, with 'z' forbidden. Since the set of possible continuations from earlier occurrence includes those from later occurrence (by ignoring intermediate characters), the maximum continuation from earlier cannot be worse. So we should pick the leftmost occurrence? But consider S = "azb". Maximum is 'z'. Only one 'z', at index 1. So fine.
But what about picking a character that is not the maximum? No.
Thus algorithm: Recursively, we can process the string from left to right, but we need to efficiently compute the solution. Since constraints up to 100k, we need O(n) or O(n log alphabet) solution.
We can think of this as building the result string by scanning from left to right, making decisions based on future availability. This is similar to constructing the lexicographically largest subsequence with distinct characters, akin to "remove duplicate letters" but with lexicographically largest instead of smallest. There is known problem: Given a string, find the lexicographically largest subsequence with all distinct characters. Approach: Use a stack or greedy with last occurrence. But we need to be careful: typical "smallest subsequence with distinct characters" (like leetcode 316) uses monotonic stack with ensuring each character appears at least once and result is smallest lexicographically. Here we want largest, and we don't need to include all characters, we can choose any subsequence with distinct characters, and we want the lexicographically largest.
Let's reason systematically.
We are to find a subsequence (preserving order) with distinct characters, maximizing lexicographic order.
Let's denote result string R.
Properties: Since lex order prioritizes early characters, R[0] = max character in S. Let's prove: Suppose optimal R starts with some char c < maxChar M. Then there exists an occurrence of M somewhere. Consider the subsequence consisting of that M alone. That string "M" is lexicographically greater than R because M > c at first position. But is "M" a valid subsequence? Yes, it's unique (single char). So R cannot be optimal. So indeed first character must be M.
Now after fixing first char = M at some index i, we have to choose subsequent characters from positions > i, with distinctness, to maximize the remainder. So the remainder should be the lexicographically largest subsequence from S[i+1:] with the constraint that characters cannot include M (since already used). But note: we might also have to consider that we could skip using M at all? No, as argued, using M gives better.
Now after picking M, we have a subproblem: Given substring T = S[i+1:], and a set of used characters U = {M}, find the lexicographically largest unique subsequence from T without using characters in U.
Observing that this subproblem has same structure: The optimal first character of the remainder (if any) should be the maximum character in T that is not in U. Because same reasoning: among possible continuations, the first character of the continuation should be as large as possible. So recursively, we want to pick the maximum allowed character in the remaining suffix, then its earliest occurrence? Wait, careful about "earliest occurrence" when there are multiple of the same char. For the first step we argued picking the leftmost occurrence of M gives more options for suffix. But after we have used some characters, we need to consider that we must pick from after the position of previously chosen character. So after we have chosen a character at index p, we move to suffix after p.
So overall algorithm: Let used = empty set. Let current position start = 0. While true:
- Find the maximum character c (allowed, i.e., not in used) that appears in the suffix S[start:].
- If no such character, break.
- Choose an occurrence of c at some index i (start <= i < n) such that we can later possibly form the continuation optimally.
- Append c to result.
- Mark c as used.
- Set start = i+1.
Now the key is: for each such chosen character, we need to pick which occurrence of the maximum allowed character to take, to allow the best continuation. Based on earlier reasoning, we should pick the leftmost occurrence of that maximum character in the current segment? But need to verify for subsequent steps.
Let's test with some examples.
Example 1: S = "abvzx". Maximum overall: 'z' (since 'z' > others). Where is leftmost 'z'? At index 3? Let's index: a(0), b(1), v(2), z(3), x(4). So start=0, max allowed = 'z', leftmost occurrence is at index 3. Choose i=3. Append 'z'. used={'z'}. start=4.
Now suffix = "x". max allowed not in used: characters: 'x' is allowed, it's max. Its leftmost occurrence at index 4. Choose it. Append 'x'. used={'z','x'}. start=5 -> break. Result "zx". That matches sample.
Example 2: S = "zaz". As earlier. Overall max = 'z'. leftmost 'z' at index 0. Choose i=0. used={'z'}. start=1, suffix="az". max allowed not in used: 'a' is max (since 'z' used). leftmost 'a' at index 1? Actually suffix "az": indices 1:a,2:z (but z is used so not allowed). So only 'a' allowed. Choose leftmost 'a' at index 1. Append 'a'. result "za". That's lexicographically largest? Could we get "zz"? No because distinct required. Could we get "z"? "za" > "z". Could we get "az"? starts with 'a' less than 'z', so no. So "za" is optimal. Good.
What about S = "bzba". Let's analyze: S = b (0), z (1), b (2), a (3). Max = 'z'. leftmost at index 1. Choose i=1, result "z", used{'z'}, start=2 suffix = "ba". Max allowed: 'b'? Actually 'b' and 'a', 'b' > 'a' and not used. leftmost 'b' in suffix: at index 2. Choose i=2, result "zb", used{'z','b'}, start=3 suffix="a". Max allowed: 'a' is allowed, leftmost at index3, choose, result "zba". Is this lexicographically largest? Let's consider alternative: if we chose 'z' at index1, then later we could choose 'a' at index3 giving "za", but "zba" > "za"? Compare "zb" vs "za"? Actually "zb" and "za" have same prefix 'z', then compare 'b' vs 'a', 'b' > 'a', so "zb" > "za". And "zba" > "zb" because longer. So "zba" is good. Could there be a subsequence like "z a"? already considered. What about "b z a"? Starts with 'b' not good. So "zba" seems optimal.
Now consider S = "abzcba". Let's see: S: a,b,z,c,b,a. Max='z' at index2. leftmost z? only one at 2. Choose i=2, suffix "cba". used{'z'}. max allowed in suffix: 'c' is max? Actually characters: c,b,a. 'c' > 'b' > 'a'. So choose leftmost 'c' at index3. result "zc". used{'z','c'}, start=4 suffix="ba". max allowed: 'b'? 'b' not used, 'a' also, max='b'. leftmost 'b' at index4? Actually suffix "ba": index4 = b, index5 = a. Choose i=4, result "zcb". used add 'b', start=5 suffix="a". max allowed 'a' (not used). choose i=5 -> "zcba". So result "zcba". Is that optimal? Let's think: Could we have "z c a"? "zcba" > "zca"? Because after 'z','c', next char 'b' > 'a', so yes. Could we have "z b a"? starts with 'z','b' < 'c'? Actually compare "z b ..." vs "z c ...": at second char 'b' < 'c', so "z c..." is greater. So "zcba" seems max. Good.
Now consider a case where the leftmost occurrence of the maximum allowed character might not be optimal because picking a later occurrence could allow us to pick a higher character later that would otherwise be blocked by the earlier occurrence? But we argued that picking earlier gives superset of suffixes; however, there is a nuance: When we pick a character, we add it to used set, forbidding it later. If we pick the leftmost occurrence of a character c, we may include in the suffix some other occurrences of c that could be used later if we hadn't picked it now. But since we are picking c now, we cannot use any c later anyway, regardless of which occurrence we pick. So we lose all c's in the suffix. But if we pick a later occurrence of c, we still lose all c's after that, but also we might retain some c's that appear between the leftmost and this later occurrence? But those c's are before the chosen occurrence; after we pick the later occurrence, we start suffix after it, so any c's before that (including the leftmost) are not in suffix. But we have already used c, so they are irrelevant. So the main difference is that picking an earlier occurrence gives a longer suffix, but also may include other characters that are not c. That seems beneficial. However, there is a potential pitfall: Suppose the leftmost occurrence of the maximum allowed character appears before some other character that is even higher but cannot be used because it would conflict with distinctness? But we are picking the maximum allowed character currently; after we pick it, we forbid it. The next step will pick the maximum allowed character in the suffix after the chosen index. If we pick the leftmost occurrence, the suffix might contain many characters, including some that are high but also some that are lower. But could picking the leftmost occurrence cause us to miss the opportunity to pick a higher character later because that higher character might be the same as the one we are about to pick? Wait, we are picking the maximum allowed character, which is c. If there is a higher character than c, it would be the maximum. So no. So c is the highest allowed. So there is no higher character in the suffix. So it's safe.
But consider scenario: There are multiple characters with same value? Not relevant.
What about the situation where the maximum allowed character appears multiple times, and picking the leftmost occurrence might cause us to lose the ability to pick a different character later because that character might only appear before a later occurrence of the maximum? Actually after picking leftmost, the suffix includes everything after it. That includes later occurrences of the same max character, but we can't use them anyway because they are forbidden. It also includes other characters that may appear before later occurrences. So it includes everything that would be included if we picked later, plus extra characters. So any continuation possible from a later pick is also possible from earlier pick because we can simply skip to the same positions. The only potential issue is that by picking earlier, we might include some characters that we might want to use earlier, but we are forced to start the suffix after the chosen index, which could be earlier than if we pick later; but we can always skip them. So earlier pick gives more options, not fewer. So leftmost occurrence is at least as good.
But wait: There is a nuance when we consider distinctness: after picking leftmost c, we mark c as used. In the continuation, we cannot use c. If we had picked a later c, we would also mark c as used, so same. So no difference.
Thus, the greedy algorithm: repeatedly select the leftmost occurrence of the maximum character among allowed (not used) from the current suffix. However, is it always optimal to always pick the maximum allowed character at each step? Let's think about a counterexample where picking a slightly smaller character now might allow picking a larger character later that would otherwise be blocked because it's the same as the maximum? But since characters are distinct in result, we cannot pick the same character twice. The maximum allowed character is the largest available. If we don't pick it now, we could possibly pick it later if it appears later. But picking it later would make the first character smaller (since we would pick something else now), which would make the overall string lexicographically smaller because the first character would be smaller. So not beneficial. But what about after we have already fixed prefix? In the recursive step, the reasoning is the same: the first character of the continuation should be the maximum allowed in the suffix, because any continuation that starts with a smaller character would be lexicographically smaller than one that starts with the maximum, regardless of what follows. And we can always achieve starting with the maximum by picking its first occurrence (or some occurrence) in the suffix. So it's optimal.
Thus the greedy approach stands.
Now we need to implement efficiently for n=100k and alphabet size=26.
Simple simulation:
- start = 0
- used = empty set
- while True:
- find the maximum character (not in used) that appears in S[start:].
- if none, break.
- find the leftmost index i >= start such that S[i] == that character.
- append character to result.
- add to used.
- set start = i+1.
But this naive approach could be O(n * alphabet) if we scan each time. Since we have at most 26 characters (distinct), we will have at most 26 iterations, because each iteration picks a new character and marks it used. So the result length <= 26. So number of iterations <= 26. For each iteration, we need to find the maximum allowed character that appears in suffix starting from current start. And then find its leftmost occurrence index >= start.
We can precompute for each character, the next occurrence positions from each index (like next[i][c] array) to answer "first occurrence of character c at or after position start". That would be O(26 * n) precomputation, which is fine (26100k = 2.6M). Alternatively, we could precompute for each position the next index of each character. Or we could precompute an array last occurrence from right to left to know if character appears after start, but we need first occurrence after start. We can precompute an array next_pos[c][i]? Usually we compute next[i][c] for i from n-1 down to 0: next[i][c] = i if S[i]==c else next[i+1][c] (with sentinel -1). This is O(n26). Then in each iteration, to find the maximum character that appears, we could check each of the 26 characters (ignoring used) and see if next[start][c] != -1. Among those, pick the maximum character. Then i = next[start][c]. That's O(26) per iteration, total O(2626) negligible. So overall O(n26) time and O(n*26) memory (~2.6M integers) which is fine. Alternatively, we can compress memory by using array of size 26 for each position, but that's 100k * 26 = 2.6M, each integer 4 bytes ~10 MB, acceptable.
Alternatively, we could compute last occurrence of each character from the right, and then simulate greedily by scanning the string once with a stack, similar to "remove duplicate letters" but for largest. Let's explore that.
The classic problem: Given a string, return the smallest subsequence that contains all distinct letters exactly once (or that contains each letter at least once?) Actually Leetcode 316: Remove Duplicate Letters (smallest lexicographic subsequence with all distinct characters, using each letter at least once). The algorithm uses a stack and last occurrence indices. Here we don't need to include all letters, we can choose any subset, but we want largest lexicographically. So we could think of the opposite: we want largest, and we are not forced to include all characters.
We could also consider: Since result will be a decreasing sequence of characters? Not necessarily: In "abvzx", result "zx" is decreasing (z > x). In "zcba", result "zcba"? Actually "zcba" is decreasing: z > c? c is less than z, but c > b > a, so it's decreasing: z > c > b > a? Actually c is less than z, so yes decreasing. In "zba", z > b > a, decreasing. In "za", z > a, decreasing. Is it always decreasing? Let's check: The greedy picks maximum char first, then maximum allowed in suffix, etc. Since we always pick the maximum allowed in the remaining suffix, and we move forward, the characters we pick will be non-increasing? Actually they could be equal? No because we forbid used characters, so they are distinct, thus strictly decreasing? Not necessarily: If the maximum character later could be larger than previous? But we pick maximum in suffix; since we have already picked some characters, the next maximum allowed could be larger than the previous? For example, consider S = "a z". Max overall = 'z', then suffix after 'z' is empty, result "z". No conflict. But if we had S = "z a", max = 'z', suffix = "a", next max = 'a' which is less than 'z', so decreasing. What about S = "b a c"? Max overall = 'c'? Actually max is 'c' at index 2? Wait "b a c": characters: b, a, c. Max is 'c'. If we pick 'c' at index 2, suffix empty, result "c". So decreasing trivially. But can we ever have a situation where the next chosen character is greater than the previous? Suppose S = "a b c". Max overall = 'c', result "c". If we had to pick something before 'c', we wouldn't because first char is max. So the first character is the absolute maximum. The second character is the maximum among allowed characters after that, which must be <= the first because if there were a character greater than first, it would be > first, but first is max overall, so no. So the sequence is non-increasing, and since distinct, strictly decreasing. So the result is a strictly decreasing sequence of characters.
Thus the result is a subsequence of S where characters are in decreasing order. So we are looking for the lexicographically largest decreasing subsequence with distinct characters. But lexicographic order for decreasing sequences: the first character dominates.
Now given that result length is at most 26, we can implement the greedy with next array.
But we must be careful: The algorithm described (pick leftmost occurrence of max allowed each time) works? Let's test some tricky cases.
Case: S = "bcabc". Distinct chars: a,b,c. The maximum character is 'c'. leftmost 'c' at index 2? Actually string: b(0), c(1), a(2), b(3), c(4). leftmost 'c' at index1. Choose i=1, result 'c', used{'c'}, start=2 suffix="abc". Max allowed in suffix: 'b'? Actually 'b' and 'a', max is 'b'. leftmost 'b' in suffix at index3 (since index2 is 'a', index3 is 'b'). Choose i=3, result "cb", used{'c','b'}, start=4 suffix="c". Max allowed: 'c' is used, so no allowed? Actually suffix is "c" but 'c' is used, so no character allowed? So result "cb". But is there a better subsequence? Consider picking 'c' at index4 instead? If we pick 'c' at index4 (rightmost), suffix after is empty, result "c". But "cb" > "c". Could we get "cba"? After picking 'c' at index1, we could pick 'a' at index2 then 'b'? But 'b' would be after 'a', but we need distinct: 'c','a','b' are distinct, but order would be indices 1,2,3 -> "cab". Lexicographically compare "cb" vs "cab": first char both 'c'; second char: 'b' vs 'a', 'b' > 'a', so "cb" > "cab". So "cb" is better. Could we get "cba"? indices 1,2,? we need 'b' after 'a' but 'a' at 2, 'b' at 3, then we would have "cab"? Actually "cba" would require order c then b then a, but after c at index1, b at index3, a after that? a after index3? There is no a after index3, only c at 4. So not possible. So "cb" seems optimal. Check if there is "cb" from indices 1 and 3 as we did. Good.
Now consider S = "abac". Chars: a,b,a,c. Max = 'c'. leftmost 'c' at index3. Choose i=3, result "c". That's only? After that no suffix. But maybe we could get "bac"? That would start with 'b', less than 'c', so "c" > "bac". So "c" is best? But consider "ac"? 'a' then 'c'? starts with 'a' < 'c', so no. So answer "c". That seems correct.
But consider S = "bca". Max='c', leftmost at index1, result "c"? Actually we could also take 'a' after? 'c' at index1, suffix "a", we can take 'a'? but used{'c'}, max allowed 'a', so we can get "ca". Compare "c" vs "ca": "ca" > "c". So we should get "ca". Our algorithm: after picking 'c' at index1, start=2 suffix="a". max allowed not used: 'a' is allowed, leftmost at index2, so we get "ca". Yes.
Now consider case where the maximum allowed character appears multiple times and picking the leftmost might cause us to lose the ability to pick a later character that is also the maximum allowed for next step because it's the same? Already considered.
But there might be a nuance: After picking a character, we restrict used set. Could it be beneficial to skip the maximum allowed character in the current suffix to allow a different character later that is not larger but might enable a longer suffix? However, lexicographic order: the first character of the suffix is most important. If we skip the maximum allowed, we would choose a smaller character as the first of the suffix, making the overall string smaller than if we had chosen the maximum, regardless of length. So not beneficial.
Thus greedy is correct.
Now we need to prove formally: Let f(S, U) be the lexicographically largest unique subsequence of S (starting from some index) with characters not in U. We claim that if we let c = max { S[i] : i >= start and S[i] not in U } (if any), and let i be the smallest index >= start with S[i] = c, then the optimal solution is c concatenated with f(S[i+1:], U ∪ {c}). This can be proven by exchange argument.
So algorithm is as described.
Implementation details:
- Input: length n (but we can ignore, just read string)
- S: string of length n, lowercase letters.
- Precompute next array: next_pos[i][26] where i from 0 to n (n sentinel). We'll create an array next of size (n+1) x 26, initialized with -1. For i from n-1 down to 0, for each char (0-25), next[i][c] = i if S[i] == 'a'+c else next[i+1][c]. Actually we can compute per character: copy from next[i+1] then set for current character. This is efficient: We'll have an array next of shape (n+1) x 26, but we can use 2D list. Since n up to 100k and 26, it's about 2.6 million entries; each entry could be an int (4 bytes) => ~10 MB, acceptable.
Simplify: We can compute next_idx array of length 26 for each position i, but we need to query next occurrence after a given start. We can also compute first occurrence after start by scanning forward, but that would be O(n) per iteration which is too much? But since only 26 iterations, scanning forward from start each time to find max char could be O(n*26) = 2.6M, which is also acceptable. Actually we could simply do: For each iteration, scan from start to n-1, keeping track of the maximum character not in used, and also note the first occurrence of that maximum? But we also need to know if after picking that first occurrence, the suffix after that may contain other characters. But we can just scan once per iteration: from start to end, we can find the maximum character (not used) present in the suffix; but we also need the index of its first occurrence. We could find the maximum char by scanning and recording the maximum char seen. Since we need to pick the leftmost occurrence of that max, we can first find the max char by scanning the entire suffix, then scan again to find its first occurrence. That's O(n) per iteration, with at most 26 iterations => O(26n) = 2.6M, also acceptable (100k * 26 = 2.6M). This is simpler and uses less memory. But we also need to update start to after the chosen index. However, scanning the whole suffix each time may lead to overall O(n * result_len) which is at most 26n = 2.6M, which is fine. But note: In each iteration, we scan from start to end, which could be O(n) each, total up to 26 * 100k = 2.6 million, which is trivial. Actually scanning 100k 26 times is 2.6 million, which is small. So we don't need fancy precomputation.
But careful: In each iteration we need to scan the suffix to find the maximum character not in used. That's O(length of suffix). Since we move start forward, total scanned characters across iterations could be up to n + (n-1) + ... ~ O(n * L) where L is number of iterations (<=26). That's about 26 * n / 2 on average, still ~1.3 million. Actually sum of lengths from start each time: first scan n, second scan up to n - something, worst-case if we pick very early indices, later scans still almost n. For example, if we pick first character at position 0, then start=1, second scan from 1 to n-1: n-1, etc. So total scanned ~ n + (n-1) + ... + (n-25) ≈ 26n - constant = 2.6 million. That's fine. So we can implement a simple loop.
But we need to be careful to efficiently check if a character is used. Since alphabet size 26, we can use a boolean array used[26].
Algorithm Steps:
- Read integer n (maybe ignore, just read string).
- Read string s.
- Initialize used[26] = false.
- Initialize result = empty list.
- Set start = 0.
- While True:
a. Determine the maximum character (as a letter) that appears in s[start:] and is not used. Let max_char = None.
For i from start to n-1:
if not used[ord(s[i]) - ord('a')]:
if max_char is None or s[i] > max_char:
max_char = s[i]
b. If max_char is None: break.
c. Find the first occurrence index pos of max_char in s[start:] (i.e., smallest i >= start such that s[i] == max_char).
d. Append max_char to result.
e. Mark used[ord(max_char)-ord('a')] = true.
f. Set start = pos + 1.
- Print result as string.
But is this always correct? Let's test with some edge cases.
Case: S = "a". max_char = 'a', not used, pos=0, append 'a', start=1, loop ends -> result "a". Good.
Case: S = "ab". max overall = 'b', first occurrence index 1, append 'b', used{'b'}, start=2. Next, suffix empty, break. Result "b". But could we have "ab"? "ab" starts with 'a' < 'b', so "b" > "ab". So correct.
Case: S = "ba". max overall = 'b', first occurrence index 0, append 'b', used{'b'}, start=1, suffix "a", max_char='a' (not used), pos=1, append 'a', result "ba". Lexicographically: "ba" > "b"? Yes because "b" is prefix. So "ba" is greater. Our algorithm yields "ba". Good.
Case: S = "bb". max overall = 'b', first occurrence index 0, append 'b', used{'b'}, start=1, suffix "b", but 'b' is used, so no max_char -> break. Result "b". Could there be "bb"? Not allowed because characters not distinct. So "b" is correct.
Case: S = "bcab". Let's run: s = b c a b. start=0, scan: chars: b (allowed), c (allowed) -> max_char = 'c' (since c > b). pos of first 'c' = 1. Append 'c'. used{'c'}, start=2. suffix = "ab". scan from index2: a (allowed), b (allowed). max_char = 'b' (since b > a). First occurrence of 'b' at index3. Append 'b'. used{'c','b'}, start=4. break. result "cb". Is there "ca"? Could have picked 'c' then 'a'? "ca" vs "cb": compare second char 'a' vs 'b', 'b' > 'a', so "cb" > "ca". Could we have "ba"? starts with 'b' < 'c', so not better. So "cb" seems optimal.
Now consider a more complex scenario: S = "cba". Our algorithm: start0, max_char='c' (first at 0), append 'c', used{'c'}, start=1, suffix "ba", max_char='b', first at 1, append 'b', used{'b'}, start=2, suffix "a", max_char='a', append, result "cba". So "cba". That's decreasing. Is there any larger? "cba" is the entire string, all distinct, so it's fine.
Now consider S = "cbac". Characters: c,b,a,c. Max overall = 'c'. leftmost 'c' at index0. Take 'c', used{'c'}, start=1 suffix = "bac". max allowed: 'b' and 'a' (c used). max='b', first occurrence at index1. Append 'b', used{'b'}, start=2 suffix="ac". max allowed: 'a' only? 'c' used, so 'a'. first at index2. Append 'a', used{'a'}, start=3 suffix="c". max allowed: 'c' used, so none. result "cba". Could we have gotten "cc"? not allowed. Could we have "cac"? not allowed distinct. Could we have "cc"? no. What about picking 'c' at index3 instead? Then start=0, we pick max='c', but if we choose index3, would that be allowed by algorithm? We are picking first occurrence, not any. If we picked later, we would get "c" only. So "cba" is better. But is there a subsequence "cbac"? not distinct. So "cba" is the answer.
But consider S = "acbca". Let's examine: a,c,b,c,a. distinct letters: a,b,c. Our algorithm: start0, scan: a (allowed), c, b, ... max_char = 'c'? characters: a, c, b, c, a. max is 'c'. leftmost 'c' at index1. Take 'c', used{'c'}, start=2 suffix="bca". scan from index2: b (allowed), c (used), a (allowed). max_char='b' (since b > a). first 'b' at index2. Take 'b', used{'b'}, start=3 suffix="ca". scan: c(used), a(allowed). max_char='a', first at index4? Actually suffix "ca": index3 = c (used), index4 = a (allowed) so pos=4. Append 'a', result "cba". Is there a better? Could we get "cba"? That's what we have. Could we get "cc"? no. Could we get "ca"? "cba" > "ca". Could we get "cb"? "cba" > "cb". Could we get "acba"? starts with 'a' < 'c', no. So answer "cba".
Now consider S = "dabc". max='d', leftmost at index0, take 'd', used{'d'}, suffix "abc", max allowed='c', first at index3? Actually "abc": a,b,c; max='c' at index3 (since string indices: 0:d,1:a,2:b,3:c). So pos=3, take 'c', result "dc". Could we get "dab"? "dab" vs "dc": compare second char: 'a' vs 'c', 'c' > 'a', so "dc" > "dab". So good.
Now consider S = "abczabc". This contains 'a','b','c','z', etc. Let's simulate: max overall = 'z'? Actually letters: a,b,c,z,a,b,c. Max = 'z'. leftmost 'z' at index3. Take 'z', used{'z'}, start=4 suffix="abc". max allowed: 'c' (since a,b,c, max='c'), first 'c' at index? suffix "abc": positions 4:a,5:b,6:c; first 'c' at index6. Take 'c', result "zc". Could there be "zcb"? After 'z' at 3, we have 'a','b','c'. We could take 'b' at 5 then 'c'? But 'c' after 'b'? Actually indices: 3:z, 4:a,5:b,6:c. We could take z (3), then b (5), then c (6) => "zbc". Compare "zc" vs "zbc": compare second char: 'c' vs 'b', 'c' > 'b', so "zc" > "zbc". Could we take z, then a, then b, then c => "zabc"? compare second char: 'a' vs 'c' of "zc", 'c' > 'a', so "zc" > "zabc". So "zc" is best. But what about taking z then a then c => "zac": second char 'a' < 'c', no. So "zc" seems optimal. But wait, is there possibility to get "zb"? second char 'b' < 'c'. So yes. So algorithm gives "zc". But could we get "zcb"? That would require 'c' then 'b', but order must be increasing indices, so cannot have c then b because b appears before c in suffix? Actually after z at index3, the remaining are a(4),b(5),c(6). To get "zcb", we would need z, then c, then b. But b is before c? Actually b index5, c index6; to have c then b, we need c index < b index, but here c after b, so cannot. So "zcb" not possible. So okay.
Now, what about a scenario where the maximum allowed character appears early, but if we pick it, we lose the chance to use a later higher character? That can't happen because it's the maximum allowed; there is no higher.
Thus the algorithm seems correct.
But wait, is there any scenario where we might want to skip the maximum allowed character to allow a longer string that starts with the same maximum but with a different subsequent character that yields a lexicographically larger overall string because the second character might be larger? For the same maximum first character, we want the lexicographically largest continuation. The continuation's first character is the maximum allowed in the suffix. So we want to maximize that. If we pick the leftmost occurrence of the maximum (first char), does it always yield the maximum possible second character? Not necessarily; we must check: The second character is the maximum allowed in the suffix after the chosen index. If we pick a later occurrence of the first maximum, the suffix after it might have a larger allowed character than the suffix after the earlier occurrence? How could that happen? Since the first maximum is the same character c, and the suffix after the earlier occurrence includes everything after that index, which includes the later occurrence and its suffix. So the set of characters available after the earlier occurrence is a superset of those after the later occurrence (specifically, it includes also characters between the two occurrences). So the maximum allowed character in the earlier suffix is at least as large as that in the later suffix. However, note that if we pick the earlier occurrence, we might be forced to use characters that appear between the two occurrences, but we are not forced; we can skip them. The maximum allowed character in the earlier suffix is the maximum of characters that appear after the earlier index and are not used yet (only c is used). That maximum could be higher if there is a high character between the two occurrences that does not appear after the later occurrence. So it could be larger. So earlier occurrence yields at least as high second character. So picking earliest occurrence is at least as good for the second character.
But could there be a scenario where picking a later occurrence yields a higher second character because the earlier occurrence's suffix contains the same maximum second character but picking it might block something? Let's imagine: Suppose after the earlier occurrence, there is a high character d, but that d also appears before the later occurrence. If we pick the earlier occurrence, we can include d as second character. If we pick the later occurrence, maybe d is not available because it's before the later index. So earlier gives more options. So better.
So the greedy of picking leftmost occurrence of maximum char each step is optimal.
Thus the algorithm is correct.
But wait: Could there be a scenario where the maximum character appears multiple times, and picking the leftmost occurrence might cause the next maximum to be lower because the leftmost occurrence's suffix includes some character that would be better to keep for later after the second character? That is, we might want to reserve a high character for later after picking a medium character to get a longer string? But lexicographic order: after we pick the first char c, we then compare the second char. We want the second char as large as possible. So we would not want to reserve a high character for later if it could be used as second char because that would increase the second char, which is more significant than any later chars. So we should use it as early as possible.
Therefore, the algorithm stands.
Now edge case: The string may contain characters but we might end up picking all 26 distinct letters if they appear in decreasing order? Actually we pick maximum allowed each time, and we move forward. Since we pick distinct characters, at most 26. So result length ≤ 26.
Now we need to implement reading input. Sample: first line length, second line string.
Implementation: We'll ignore length maybe, but we can read both.
We'll implement the simple O(26 * n) approach.
Pseudo:
def strongest_unique_subsequence(s):
n = len(s)
used = [False]*26
result = []
start = 0
while True:
max_char = ''
# find the maximum character not used that appears in s[start:]
for i in range