We are given two strings s (the favorite pattern) and t (the actual typed string). They have equal length n (n ≤ 1000). The problem statement: Santa suspects that some pairs of keys swapped places: each key is either in its correct place, or on the place of another key, which is located exactly where the first key should be. In other words, we have a permutation of keys that is a composition of disjoint swaps (i.e., an involution with no fixed points? Actually it says: "each key is either on its place, or on the place of another key, which is located exactly where the first key should be." That implies that if key A is not in its correct place, it is swapped with some key B, and that key B is at A's position, and A is at B's position. That is, the mapping from intended key to typed key at each position is such that if we consider the "keyboard mapping" from letter (intended key) to what appears when you press that key? Let's interpret carefully.
We have a keyboard: each key is a physical key cap with a label (the letter). Santa reassembled the keyboard, possibly swapping some keys. So after reassembly, when Santa presses the key that is supposed to be 'a' (i.e., intends to type 'a'), he actually types whatever letter is now on that physical key position. But the problem describes: "some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be." So we have a set of pairs (x, y) such that the keys labelled x and y are swapped. That means: if you press the key that is supposed to be x (i.e., the position where x should be), you actually get y because that key now has y's label; similarly, pressing the position for y gives x. For keys not involved in any swap, pressing them gives the correct letter.
Thus there is a mapping f: intended letter -> typed letter that is an involution (i.e., f(f(a)) = a) and f(a) = a for letters not in any swap. But careful: The mapping is defined on the set of letters (the alphabet). The swapping is at the key level: two keys exchange places. So the mapping from intended letter to typed letter: if letter a's key is swapped with letter b's key, then when you intend a you get b, and intend b you get a. So yes, f is an involution (f = f^{-1}) and can have fixed points (when not swapped). Also, no letter can be involved in more than one swap, so f has cycles of length at most 2.
Now Santa types his favorite pattern s, looking only at the keyboard. That is, he thinks the keys are in correct order, so he presses keys according to the pattern s (i.e., he intends to type s). But because of swapped keys, what actually appears is t. So t[i] = f(s[i]) for each i, where f is an involution (with possible fixed points, f(a)=a for most letters) representing the swap pairs.
Given s and t, we need to determine if there exists such an involution f (with no letter appearing in more than one swap, i.e., f is a matching on the alphabet) that satisfies t[i] = f(s[i]) for all i. And if yes, output any such set of swap pairs (i.e., all unordered pairs {a,b} with a != b such that f(a)=b and f(b)=a). It says: "Each key must occur in pairs at most once." So no letter appears in more than one pair. So f is a partial involution with no fixed points among swapped letters (i.e., swapped letters map to each other) and others map to themselves.
We need to find if such f exists and if so output the pairs.
Observations: For each position i, we have s[i] and t[i]. If s[i] == t[i], that imposes that f(s[i]) = s[i] => the key s[i] is not swapped (or if swapped, would map to something else, but could it be that s[i]==t[i] even if swapped? If s[i] and some other b are swapped, then f(s[i]) = b != s[i] unless b = s[i], but that's fixed. So yes, s[i]==t[i] implies f(s[i]) = s[i], meaning s[i] is not involved in any swap (or it could be that s[i] maps to itself? But we consider swapping: a key can't swap with itself. So f(a)=a means not swapped. So if s[i]==t[i], then s[i] must be a fixed point.)
If s[i] != t[i], then we require f(s[i]) = t[i] and by involution property f(t[i]) = s[i]. So that implies that s[i] and t[i] must be swapped with each other. However, there could be conflicts: For example, we could have a position i where s[i]=a, t[i]=b, and another position j where s[j]=a, t[j]=c, with b!=c. Then we would need f(a) = b and f(a) = c, impossible. Similarly, if s[i]=a, t[i]=b and some position with s[j]=b, t[j] should be a if consistent, but if we have s[j]=b, t[j]=d with d != a, then conflict because f(b) must equal a from first pair but also d from second => conflict unless a=d. So there are consistency constraints.
Thus we need to check if there exists an involution f consistent with all given (s[i], t[i]) pairs.
We can think of building a graph where each node is a letter. For each i, we have an edge from s[i] to t[i] (directed? but due to involution, we need to interpret). Actually the constraint is that there is a mapping f such that f(s[i]) = t[i]. And f is an involution (f(f(x)) = x) and f has no cycles length >2 (i.e., each node's image is either itself or a distinct node, and if f(x)=y and y != x, then f(y)=x). So this essentially enforces that the relation between letters is symmetric and functional.
Thus we can think of constructing f from constraints: For each position i, we get that f(s[i]) = t[i]. If s[i]==t[i], we get f(s[i]) = s[i], so s[i] fixed. If s[i]!=t[i], we get f(s[i])=t[i] and therefore also f(t[i])=s[i]. So we can treat that as two constraints: f(a)=b and f(b)=a.
Given the set of constraints, we need to check if there is a consistent f that is an involution.
We can model as a graph where each directed constraint f(a)=b. Since f is a function, each a can have at most one b such that f(a)=b. The constraints must not conflict: For each a, all constraints on f(a) must agree.
Also the involution property gives additional constraints: if f(a)=b (with a!=b) then f(b)=a, which must not conflict with any other constraints on b. So these must be symmetric.
Thus essentially, the constraints force certain pairs to be swapped, and all other letters fixed.
But there is an extra nuance: the constraints may be inconsistent in a more subtle way? For example, we could have constraints that force a chain: f(a)=b, f(b)=c, and f(c)=a? This would be a cycle of length 3. But is that possible given that we also require f(b)=a from the first? Actually if f(a)=b then by involution we must have f(b)=a, so any constraint that gives f(b)=c would conflict unless c=a. So any cycle longer than 2 is impossible. So the constraints will either be consistent with a matching, or produce a conflict.
But we are not given the entire mapping; we are just given s and t. So we need to see if there exists an involution f that fits. Actually the existence is determined by consistency of the necessary constraints derived from the pairs. However, there could be multiple ways to assign f for letters not appearing in s? Wait, letters that do not appear at all can be either fixed or swapped arbitrarily? But the requirement: "Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes." That means we only care that the typed pattern matches the favorite pattern when using the keyboard. So we only need to ensure that for each letter that appears in s, the mapping f is defined and matches t. For letters that do not appear in s, they can be anything (but the problem statement: "Determine which pairs of keys could be mixed." It expects us to output the actual swap pairs that we think are necessary. But we need to output a set of pairs such that if we swap those keys, the keyboard will correctly type s as t. However, we are free to not include letters that never appear? But the mapping f must be an involution on all letters, but we can assume that any letter not appearing can be left unchanged (fixed). That's fine because they are not involved in typing s. So we can set f(a)=a for letters not appearing. However, there is a nuance: Suppose some letter appears in t but not in s? But since t is typed output, it could contain letters that are images of s letters, so they appear. But those letters might need to be swapped with some s letters; they appear as t. So they will appear in constraints because they are either s or t. Actually each letter that appears either in s or t could be involved. But if a letter appears only in t but not in s, then there must be some s[i] mapping to it, so that letter appears as t[i] for some i, so it is involved. So all letters that appear are in the constraints.
Thus we need to consider the set of letters that appear in either s or t. For each such letter, we must define f consistent with constraints.
Thus algorithm:
- Let n = length(s)=length(t).
- Initialize mapping dict f: letter -> None initially.
- For each i from 0 to n-1:
a = s[i], b = t[i].
If a == b:
if f[a] is None: set f[a] = a (fixed).
else if f[a] != a: conflict -> impossible.
else:
if f[a] is None: set f[a] = b.
else if f[a] != b: conflict -> impossible.
if f[b] is None: set f[b] = a (by involution, we deduce that f(b)=a).
else if f[b] != a: conflict -> impossible.
But wait, careful: The deduction f(b)=a is required for f to be an involution and consistent. However, is it automatically forced? Let's consider: The existence of a mapping f that satisfies f(a)=b, and we also know f must be an involution. So if we define f(a)=b (b != a), then necessarily f(b)=a. But could there be a scenario where we don't need to set f(b)=a because we could have some other arrangement? No, because for f to be an involution, if f(a)=b then f(b)=a. So any valid f must satisfy that. So if we have a constraint that gives f(a)=b, then we must also enforce f(b)=a. So we can directly add that as a constraint.
But careful: There is also the possibility that we might later encounter a case where we have f(b)=something else, which would conflict. That's fine.
Thus the above algorithm seems to check consistency.
But is it sufficient? After processing all constraints, we must also ensure that the mapping we end up with is an involution (i.e., if f(a)=b and b != a, then f(b)=a must hold, which we already enforce). Also we must ensure that no letter is involved in more than one swap. But our enforcement ensures that because if we set f(a)=b and f(b)=a, that's a pair. However, could we have a scenario where we set f(a)=b, and later we encounter a position that gives f(b)=a as well? That is consistent. But what about a scenario where we have f(a)=b, and f(c)=b? That would conflict because b can only map to one thing (since f is a function). In our algorithm, when we set f(b)=a initially, if later we have a constraint f(b)=c, it would check and conflict. So that's covered.
But there is a nuance: What about a situation where we have s[i]=a, t[i]=b, and s[j]=b, t[j]=a? That's consistent and adds the same constraints.
So after processing all positions, we have a partial function f. For any letter that doesn't appear in any constraint? But all letters that appear in s or t appear in constraints. However, some letters might appear only as t and never as s, but we set f for them from the deduced constraints. So after processing, all letters that appear will have a mapping. But there might be letters that appear but we only set f for them as a result of being t? Yes, we set f(b)=a when processing a->b. So they get a mapping.
Now, are there any scenarios where the mapping we have is not a valid involution because of something like f(a)=b, f(b)=a, but also f(a)=a? No, because that would conflict earlier. So okay.
But wait: Could there be a scenario where the mapping we derived from the constraints is consistent as a function but still cannot be realized as a set of swaps because of a "cycle" of length 2? Actually length 2 is fine. Or maybe we could have a scenario where f(a)=b, f(b)=a, but also f(c)=b? That would be conflict. So all good.
Thus the necessary and sufficient condition for existence is that for all i, the constraints f(s[i])=t[i] are consistent with an involution, i.e., we never have contradictory assignments, and also we never have a scenario where a letter maps to two different letters, or a letter is forced to map to itself and also to another letter.
But is there any case where we need to consider something like: s[i]=a, t[i]=b, and s[j]=a, t[j]=b again, fine. Or s[i]=a, t[i]=b, and s[j]=b, t[j]=c with c!=a. That would give f(a)=b and f(b)=c, but from involution, f(b) must be a, so conflict unless c=a. So that's caught because when processing j, we would set f(b)=c, but we already have f(b)=a from previous deduction, so conflict.
So algorithm: iterate through i from 0..n-1:
a = s[i]; b = t[i];
if a == b:
if map.get(a) is None: map[a]=a.
elif map[a]!= a: -> impossible.
else:
if a not in map: map[a]=b.
else if map[a]!=b: impossible.
if b not in map: map[b]=a.
else if map[b]!=a: impossible.
After processing all positions, we have a mapping f defined on a set of letters L (those that appear). But we must also ensure that for any a where f(a)=b and b!=a, we have f(b)=a (which is already enforced by the above because we set f(b)=a). So mapping is an involution.
But wait: There is a subtle case: Suppose we have s[i]=a, t[i]=b, and s[j]=c, t[j]=a. Then we set f(a)=b, f(b)=a; also from second: f(c)=a, but we already have f(a)=b, and f(a) can't be both b and a? Actually careful: For j: s[j]=c, t[j]=a => implies f(c)=a. That's fine; we set f(c)=a. Also by involution, we would require f(a)=c? Because if f(c)=a, then to be involution we need f(a)=c (since a!=c?). Actually if f(c)=a and a != c, then for f to be an involution we must have f(a)=c. But we already have f(a)=b from earlier. That would cause conflict unless b=c. So this should be caught. In our algorithm, when processing j (c->a), we will:
- set f(c)=a.
- Then we will also set f(a)=c (since we deduced f(a) from involution). But we already have f(a)=b from earlier. So we will compare map[a] (which is b) to c, and since b != c (unless equal), conflict. So caught.
But we need to ensure that we do that deduction for both directions whenever we set a mapping for a->b where a!=b. In our algorithm, we set both f[a]=b and f[b]=a. So for the second pair c->a, we will set f[c]=a, and then set f[a]=c. But if f[a] already exists as b, we check and conflict. So indeed.
However, there is an edge: if we process a->b first, we set f[a]=b and f[b]=a. Then later we process c->a: we see f[c] not set, set f[c]=a. Then we attempt to set f[a]=c, but f[a] is already b, so conflict unless b==c. Good.
Thus the algorithm works.
Now, after constructing such a mapping, we must output the pairs of swapped keys. The mapping f gives for each letter either fixed (f(a)=a) or swapped (f(a)=b with b>? Actually we need to output each pair only once. So we can iterate over letters (e.g., 'a'..'z') and for each letter a, if f(a) is defined and a < f(a) (to avoid duplication) and a != f(a), then that is a swap pair.
But careful: The mapping might not be defined for some letters; we can ignore. Also we must ensure that the mapping is consistent with being an involution; but we already ensured.
One more subtlety: Could there be a case where the mapping derived from constraints is not an involution because of self-mapping but later we have a conflict? Already handled.
But is there any possibility that the mapping derived from constraints is consistent as a function but violates the condition that each key can only be in at most one pair? That condition is exactly the involution property: each key appears in at most one swap, i.e., if a maps to b (b != a), then b maps to a; and no other mapping from a or b. Our mapping ensures that. However, there is a nuance: what if we have a letter a such that f(a)=b, and also f(b)=a, but also maybe we have a letter c such that f(c)=a? That would mean a is mapped to b and also from c to a; that would mean a is the image of c, but since f is a function, f(a)=b is okay; but does that mean key a is involved in more than one swap? The key a is physically swapped with b. If also c maps to a, that would imply that when you intend to type c, you get a, but since a is physically swapped with b, then the key that prints a is actually at position originally for a? Let's think: The mapping f is from intended letter to typed letter. If f(c)=a, that means when Santa intends to type c, he gets a. That would imply that the key at position c (the key cap that should be c) actually prints a. But the key that prints a is either at its own position (if not swapped) or at b's position if swapped with b. For f(c)=a to be possible, the key that prints a must be at the position for c. That would mean that key a is not at its own position; it is swapped with b. So where is key a? It is at b's position. So if key a is at b's position, then the key at c's position prints a, meaning there is a key labelled a also at c? That would require two keys labelled a, impossible. So f(c)=a with c != a and c != b is impossible because the physical key labelled a can only be in one place. But wait, careful: The mapping f is not directly about physical key positions; it's about the result of pressing the key that is supposed to be a certain letter. But let's derive constraints from physical swaps.
Consider physical keys: each key has a letter printed on it. Initially, the keyboard has keys in correct positions: key with letter X is at position X. After swapping some pairs, keys move. The operation: When Santa wants to type letter X, he presses the key at position X (the location where X should be). That key now has some letter Y (the label of the key now at that position). So typed letter = label of key at position X.
So let’s define the physical permutation p: the key that originally was at position A (i.e., with label A) is now at position p(A). Since we only swap pairs, p is an involution (disjoint swaps) with p(A) = A for keys not swapped. But careful: The mapping from intended to typed is: we press position A, we get the label of key currently at position A. That label is the original letter of the key that is now at A. If originally key B was at position B, after swapping, it moves to p(B). So the key at position A is the key such that p(original label?) Actually it's easier: Let q be the permutation of keys: q maps a key's original label to its new position. If we swap keys A and B, then key A goes to position B, and key B goes to position A. So q(A)=B, q(B)=A, and for others q(C)=C. Then when we press position X, we get the key located at X, which has label L such that q(L) = X (i.e., the key whose new position is X). So typed letter T for intended X satisfies q(T)=X => T = q^{-1}(X). Since q is an involution (q = q^{-1}), we have T = q(X). Indeed, because q is its own inverse: q(q(X)) = X. Check: For swapped A and B: q(A)=B, so when you press A (intended A), the key at position A is the key that moved to A, which is B (since q(B)=A). So typed letter = B = q(A). For non-swapped C: q(C)=C, typed = C. So indeed f = q, the permutation of keys. So f is exactly the swapping permutation: f(A) is the key that originally was at A moves to f(A)? Actually from above, typed letter = f(A) where f = q. And q is an involution with no fixed points for swapped letters? Actually it can have fixed points (non-swapped). So indeed f is an involution on the set of letters (alphabet) with f(A) = where key A moves to? Wait careful: q(A) is the new position of key A. But typed when pressing position A is the key that is now at position A, which is the key whose q equals A, i.e., the key B such that q(B)=A => B = q^{-1}(A) = q(A) because q is involution. So typed = q(A). So f(A) = typed = q(A). So the mapping f is exactly the permutation of keys (where each key goes). And that permutation must be an involution composed of disjoint swaps (including identity). So f is an involution.
Now, suppose we have f(c)=a and f(a)=b with a != b and a != c, and b != c. Is that possible under a composition of disjoint swaps? Let's test: If f(a)=b, that means key a moved to position b (so key a is now at position b). Also, f(b)=a (by involution) means key b moved to position a. So keys a and b swapped. Now consider f(c)=a. That would mean when you press c, you get a. So the key at position c is labelled a. But key a is already at position b (since swapped with b). So can key a also be at position c? No, each key is unique. So impossible. Thus any mapping where a letter appears as the image of more than one distinct source (other than itself) is impossible. However, does our constraint system catch that? Let's see. If f(c)=a and f(a)=b, then we have f(a)=b and f(c)=a. From involution, f(a)=b implies f(b)=a. Also f(c)=a implies f(a)=c? Actually if f(c)=a, then because f is an involution and a != c, we must have f(a)=c. But we already have f(a)=b, so conflict unless b=c. So it's caught because we enforce that when we set f(c)=a, we also set f(a)=c. So indeed, our algorithm will catch such conflict. Good.
Thus the mapping must satisfy that if f(x)=y and y != x, then the only occurrence of y as an image is from x. So essentially, each swapped pair (x,y) is isolated: x maps to y, y maps to x, and no other maps to either x or y. In our constraint propagation, this is ensured.
Thus the algorithm described is correct.
But we need to check some edge cases:
-
What if we have s[i]=a, t[i]=a (so fixed). That sets f(a)=a. Later if we see s[j]=a, t[j]=b with b != a, then conflict because we already set f(a)=a. So caught.
-
What if we have s[i]=a, t[i]=b (b!=a) and also s[j]=b, t[j]=b? That would set f(b)=b, but from earlier we set f(b)=a. Conflict because f(b) would be both a and b. So caught.
-
What if we have s[i]=a, t[i]=b and s[j]=a, t[j]=b? That's fine, just duplicate.
-
What if we have s[i]=a, t[i]=b and s[j]=b, t[j]=a? That sets same constraints.
-
What about letters that never appear? They can be fixed arbitrarily; we can ignore them.
Thus existence condition is simple: no contradictions.
But wait: There is also the possibility that the derived mapping f might have a cycle of length 2 but also self-mapping? Already covered.
Now, what about the requirement: "Each key must occur in pairs at most once." That's already enforced.
Now, output: first line integer k = number of pairs (i.e., number of unordered swaps where f(a)=b and a!=b). Then k lines, each with two letters (space separated). Order of pairs and order within a pair can be arbitrary. The only condition: All printed letters must be distinct. That is, the set of letters appearing in the output should have no duplicates. Since each letter can be in at most one pair, that's automatically satisfied if we output each swap pair exactly once. So we just need to output each unordered pair once.
Now, is it possible that the derived mapping f has some letters that are fixed (f(a)=a) and also some swapped pairs? Yes.
Thus solution seems straightforward.
But wait, the problem statement: "Determine which pairs of keys could be mixed." Could there be multiple valid sets of swaps? Possibly, but we output any. Our algorithm yields a specific set (the one forced by the constraints). However, could there be cases where constraints do not fully determine f? For example, if s and t are such that no mismatch occurs? That is, s = t. Then f could be identity, which yields k=0. That's one valid answer. But could there be another answer with some swaps that still produce the same t? For s = t, if we swap some pair of letters that never appear? If a letter never appears in s, swapping it with another letter that never appears in s would not affect typing s, because those keys are never pressed. But would that be allowed? The problem asks: "Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes." So if he swaps two keys that are not used in the pattern, then when typing the pattern, he still gets the correct output. So such swaps could be present, and we would still get t = s. So there could be multiple valid sets of swaps. However, the problem says "Determine which pairs of keys could be mixed." It might ask us to output any valid set; we can choose the simplest: output none (k=0). That's allowed because it says "If there are several possible answers, print any of them." So output 0 is fine. However, is it always valid to output k=0 when s = t? The mapping f must be identity on all letters that appear. But what about letters that don't appear? They could be swapped among themselves but we don't need to output them. The problem likely expects to output only the swaps that are necessary? But they allow any, so identity is okay. So we can output 0. But note: They require "All printed letters must be distinct." With k=0, no letters printed, so okay.
But what about cases where there are some mismatches and the constraints force some swaps, but there could be additional swaps on letters not appearing? Could we add extra swaps that don't affect s? For letters not appearing in s, swapping them among themselves does not affect the typed string. But would that violate the condition that "Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be." That describes the actual state of the keyboard. Santa wants to restore the correct order. We are asked to determine which pairs could be mixed (i.e., to output the pairs of keys that should be swapped to fix the keyboard). Usually, we want to find a set of swaps that explains the observed typing. If there are extra swaps on unused keys, that would also explain the typing because they don't affect s. So there could be multiple valid sets. But the problem says "print any of them." So we can choose the minimal one (only forced swaps). That's fine.
Now, is there any scenario where the forced swaps themselves are not a matching? They are forced to be a matching due to constraints. So okay.
Thus algorithm: Build mapping array f[26] initially -1 meaning unknown. For each i:
a = s[i]; b = t[i];
if a == b:
if f[a] == -1: f[a] = a (or assign some code to indicate fixed, e.g., f[a] = a)
else if f[a] != a: impossible.
else:
if f[a] == -1: f[a] = b; else if f[a] != b: impossible.
if f[b] == -1: f[b] = a; else if f[b] != a: impossible.
But careful: f[a] = b; f[b] = a. However, if later we encounter a case where a maps to b again, it's fine.
After processing all, we also need to consider letters that appear but for which mapping might not have been set? Actually all letters that appear will have been set either as source or target. But there might be letters that appear only as target and the source constraint didn't set them? In the else branch, we set both. In the equality branch, we set the source. So any letter that appears in either s or t will appear in some i either as s[i] or t[i] and thus get a mapping. However, could there be a letter that appears only as t[i] in a position where s[i] == t[i]? That would be equality, so it appears as s[i] as well (since equal). So it's covered. If it appears only as t[i] where s[i]!=t[i], then we set it in the else branch. So yes, all letters that appear get mapping.
Now, there is a subtle corner: Could there be a situation where f[a] = b, and f[b] = a, but later we see a position where s[i]=a, t[i]=a? That would be conflict as we'd set f[a]=a while already f[a]=b. So that is caught.
Thus after constructing mapping, we can also check for consistency: for each letter a where f[a] is defined, we must have f[f[a]] = a (if f[a] != a). But our propagation ensures that? Let's verify: If we set f[a]=b and a!=b, we also set f[b]=a. So that holds. However, what about a case where we set f[a]=b, but we never set f[b] due to some oversight? That can't happen because we explicitly set f[b]=a. So f is defined for b as well. So the involution condition holds.
But we might need to handle a situation where a letter appears but we don't have f defined? Possibly if a letter appears only as t[i] where s[i]==t[i]? That's equality; s[i] appears so it's defined. So fine.
Now, after we have f, we need to output the pairs. But we must ensure that the mapping we have does not include any letter that appears more than once? Already ensured. So we just iterate over letters (e.g., 'a'..'z') and for each letter a, if f[a] is defined and f[a] > a (or a < f[a] to avoid duplicates) and a != f[a], output a and f[a]. However, careful: If we output for each a only when a < f[a], we might output a pair where f[a] != a but f[a] might be less than a, then the other side will output when we consider that letter. To avoid duplicates, we can use a visited set. For each letter a, if not visited and f[a] defined and f[a]!=a, then output pair (a, f[a]), and mark a and f[a] visited.
But what about letters that are fixed (f[a]=a)? We don't output.
But wait: The problem says "All printed letters must be distinct." That means each letter appears at most once in the output lines. Since each letter is in at most one swap, that's okay.
Now, let's test with examples:
Example 1:
s = helloworld, t = ehoolwlroz
Let's compute mapping step by step.
Indices:
0: h -> e: set f['h']='e', f['e']='h'
1: e -> h: but f['e'] is already 'h' (ok), f['h'] is 'e' (ok). Also equality? e->h matches, so consistent.
2: l -> o: set f['l']='o', f['o']='l'
3: l -> o: same as above? Actually index 3: s[3]=l, t[3]=o (since t="ehoolwlroz", let's index: 0:e,1:h,2:o,3:o,4:l,5:w,6:l,7:r,8:o,9:z). Wait check: s = "helloworld": indices:0 h,1 e,2 l,3 l,4 o,5 w,6 o,7 r,8 l,9 d? Actually "helloworld": h e l l o w o r l d. Yes. t = "ehoolwlroz": e h o o l w l r o z. So:
i=0: h->e => set f[h]=e, f[e]=h.
i=1: e->h => f[e] already h, ok; f[h] already e, ok.
i=2: l->o => set f[l]=o, f[o]=l.
i=3: l->o => f[l] already o, ok; f[o] already l, ok.
i=4: o->l => f[o] already l, ok; f[l] already o, ok.
i=5: w->w? s[5]=w, t[5]=w? t[5] is w? Actually t[5]=w? Let's index t: 0 e,1 h,2 o,3 o,4 l,5 w,6 l,7 r,8 o,9 z. So i=5: w->w => set f[w]=w (fixed).
i=6: o->l => f[o] already l, ok; f[l] already o, ok.
i=7: r->r? s[7]=r, t[7]=r => set f[r]=r.
i=8: l->o? s[8]=l, t[8]=o? t[8]=o, yes. f[l] is o, ok; f[o] is l, ok.
i=9: d->z => set f[d]=z, f[z]=d.
Now mapping: h-e, e-h, l-o, o-l, w-w, r-r, d-z, z-d.
Thus swapped pairs: (h,e), (l,o), (d,z). That matches example output: 3, h e, l o, d z (order could differ). So fine.
Example 2:
s = hastalavistababy, t = same. Then for each i s[i]==t[i] => set f[each letter]=itself. So all fixed. So output 0. Good.
Example 3:
s = merrychristmas, t = christmasmerry. Let's test quickly. n=?
merrychristmas length? "merry" (5) + "christmas" (9) =14. t = "christmasmerry"? that's 9+5=14.
We suspect impossible. Let's see if our algorithm finds conflict.
We need to compute mapping. Process each position.
Write s and t aligned:
s: m e r r y c h r i s t m a s? Actually "merrychristmas": m e r r y c h r i s t m a s? Let's write correctly: "merry" = m e r r y; then "christmas" = c h r i s t m a s. So s = m e r r y c h r i s t m a s (14 letters). t = "christmasmerry": c h r i s t m a s m e r r y. So align indices:
i0: s[0]=m -> t[0]=c => f[m]=c, f[c]=m.
i1: s[1]=e -> t[1]=h => f[e]=h, f[h]=e.
i2: s[2]=r -> t[2]=r => set f[r]=r? but careful: this is equality, but we already have? f[r] not set yet, so set f[r]=r.
i3: s[3]=r -> t[3]=i => now s[3]=r, t[3]=i. But f[r] is already set to r (from i2). So conflict because we have f[r]=r but now need f[r]=i. So impossible. Hence -1. So matches.
Thus the simple algorithm works for examples.
Now, let's consider more subtle cases.
Case: s = "ab", t = "ba". Then i0: a->b => f[a]=b, f[b]=a. i1: b->a => f[b] already a, f[a] already b, ok. So mapping yields swap (a,b). Output 1 pair. That's plausible.
Case: s = "ab", t = "ac". i0: a->b => f[a]=b, f[b]=a. i1: b->c => f[b] currently a, but need f[b]=c -> conflict, because a!=c. So impossible.
Case: s = "ab", t = "aa". i0: a->b => f[a]=b, f[b]=a. i1: b->a => f[b] already a, ok. But wait, t[1]=a, s[1]=b. That's fine. So mapping: a<->b. But t[1]=a, so from b typed a, consistent. So s="ab", t="aa" is possible? Let's think: If a and b are swapped, then pressing a yields b, pressing b yields a. So typing "ab" yields b a? Actually type a -> b; type b -> a. So "ab" would yield "ba", not "aa". To get "aa", you'd need to type a and then something that yields a. If a and b swapped, pressing a gives b, pressing b gives a. To get "aa", you would need to press a (gives b) and then press something that gives a, e.g., press b gives a. So "ab" gives "ba", not "aa". But we have s="ab", t="aa". Wait, we processed: i0: a->b => typed b, not a. So t[0] must be b, but it's a, so conflict. Oops, I mis-simulated: For s="ab", t="aa", i0: a->? t[0]=a, so a==a? Actually s[0]=a, t[0]=a, so they are equal. But in our earlier step I incorrectly assumed a->b. Let's recalc properly: s="ab", t="aa". i0: s[0]=a, t[0]=a -> a==a, so f[a]=a (fixed). i1: s[1]=b, t[1]=a -> b!=a, set f[b]=a and f[a]=b? But f[a] already a from i0. So conflict: f[a] would need to be b but is a. So impossible. Good.
Case: s = "abc", t = "acb". i0: a->a? Actually s[0]=a, t[0]=a -> fixed a. i1: b->c => set f[b]=c, f[c]=b. i2: c->b => f[c] already b, f[b] already c, ok. So mapping: a fixed, b<->c. That works: a maps to a, b<->c. So typing "abc": a->a, b->c, c->b => a c b = "acb". Yes. So output pairs: b c. Good.
Now, consider case where there could be a possibility to have multiple valid sets. For example, s = "ab", t = "ba". The forced mapping is a<->b. Could we also have additional swaps like c<->d? Since c,d not used, the typed string remains same. So there are many possible sets. But we output minimal (only forced) is fine.
Now, is there any scenario where forced mapping includes a letter mapping to itself (fixed) but also that letter appears as a target for some other mapping? That would be conflict, as we handle.
Thus the solution is simply building the mapping.
But wait, is it always enough to just propagate constraints from each position in any order? Yes, because constraints are functional and symmetric. There's no need for additional reasoning.
Now, let's check boundary: n up to 1000, alphabet 26, trivial.
Implementation details:
- Use integer indexes 0-25 for letters.
- Create array f of size 26, initialize to -1 (or 26 maybe using -1 to indicate unassigned).
- Also maintain a boolean array exists to mark letters that appear? Not necessary.
Pseudo:
f = [-1]*26
for i in range(n):
a = ord(s[i]) - ord('a')
b = ord(t[i]) - ord('a')
if a == b:
if f[a] == -1:
f[a] = a
elif f[a] != a:
print(-1); return
else:
# set f[a]=b
if f[a] == -1:
f[a] = b
elif f[a] != b:
print(-1); return
# set f[b]=a
if f[b] == -1:
f[b] = a
elif f[b] != a:
print(-1); return
After loop, we have mapping.
But we also need to check for any indirect inconsistencies? For example, what if f[a]=b and f[b]=a, but also f[a]=a? Already handled. But is there any scenario where f[a]=b, f[b]=a, but also f[a]=b is fine, but maybe a letter c maps to a? That would be f[c]=a, and then by involution we would need f[a]=c. But f[a] is already b, so conflict would have been caught when processing the position that gave f[c]=a, because we would have attempted to set f[a]=c. Indeed, the algorithm will catch it.
Thus it's consistent.
Now, after building f, we might also need to ensure that f is an involution for all defined letters. For example, consider a situation where we only have a constraint from a to b (so we set f[a]=b and f[b]=a) and later we have a constraint from c to d (f[c]=d, f[d]=c). That's fine.
Now, what about a scenario where we have f[a]=b, but later we encounter a position that gives f[a]=b again (fine) but what about encountering a position that gives f[b]=a again (fine). So no problem.
Thus the algorithm is correct.
But is there any scenario where the mapping derived from direct constraints does not yield a consistent involution but there exists some other involution that satisfies the (s,t) pairs? Could it be that the mapping we derive by enforcing f(b)=a immediately might be too strict? Let's consider if we could have a scenario where we don't require f(b)=a if we have not yet deduced it, but later we might choose a different assignment that still satisfies all positions? For example, suppose we have positions: (a->b) and (b->c) with a,b,c distinct. According to our algorithm, processing (a->b) sets f[a]=b and f[b]=a. Then processing (b->c) would see f[b] is already a, conflict. But is there any involution f that satisfies both constraints? We need f(a)=b and f(b)=c. Since f is involution, f(b)=c implies f(c)=b. And f(a)=b implies f(b)=a. So we would need f(b)=a and f(b)=c, so a=c, impossible unless a=c. So no involution can satisfy both. So our algorithm correctly says impossible.
Now consider scenario with three letters a,b,c and positions: a->b, b->a, a->c? That's contradictory, we would have f(a) must be both b and c. So impossible.
Now, consider scenario where we have only one position: a->b. Then we would set f[a]=b and f[b]=a. That is forced? Could there be an involution where f[a]=b, f[b]=a? Yes. But could there be another involution where f[a]=b but f[b] is something else? No, because involution forces f(b)=a. So it's forced. So correct.
Consider scenario: a->a (equality). That forces f[a]=a, which is the only possibility (since if a were swapped with someone else, f[a] would be that someone else, not a). So correct.
Thus forced mapping is exactly the unique mapping if exists. Because each constraint imposes specific values, and due to involution they propagate. There is no freedom for letters that appear in any constraint. The only freedom would be for letters that never appear, which we can leave fixed. So the mapping derived is essentially unique for the appearing letters.
But wait, could there be a scenario where there is more than one valid involution consistent with the given pairs? Consider s="ab", t="ba". The forced mapping is a<->b. Could we also have f such that a<->b plus additional swaps on unused letters? That is still same mapping on appearing letters, but with extra swaps on non-appearing letters. But those extra swaps are not reflected in the mapping for appearing letters. In our mapping we only set values for letters that appear. For letters that don't appear, we leave them undefined (-1). So our output could be just the forced swaps among appearing letters. That's fine.
But what if there is an alternative mapping that differs on appearing letters but still satisfies all constraints? Let's try to see if any ambiguity can arise. Suppose we have a scenario where there is a position with a->b and also a position with a->b (duplicate). That's same. Could there be a scenario where constraints only specify f(a)=b but do not involve b elsewhere? That forces f(b)=a. No alternative. Could there be a scenario where constraints only involve letters that are fixed? That forces them fixed. So the mapping on appearing letters is forced.
But wait, consider a scenario where we have positions: a->b and also c->c (c fixed). That's fine. No ambiguity.
Thus the mapping is forced if it exists.
So the algorithm is correct.
Now, let's double-check the problem statement: "Each key must occur in pairs at most once." That is a condition on the output: we must ensure that each key appears in at most one pair. Since our mapping is a matching, it satisfies. The problem also says: "All printed letters must be distinct." So we must not output duplicate letters across pairs. Our output method (each unordered pair once) ensures that.
Edge Cases:
- n=1: s = "a", t = "b". Then f[a]=b, f[b]=a. Output pair (a,b). That's valid.
- n=1: s = "a", t = "a". Output 0.
- s = "a", t = "a", but also we could output a swap pair involving a? No, because a would have to map to something else. So only identity works.
Now, what about letters that appear in both s and t but as part of a swap cycle where mapping is forced but also could be resolved by multiple swaps? For example, suppose we have s = "ab", t = "ba". The mapping forced is a<->b. Could we have a different involution that also produces the same effect? For instance, could we have f(a)=c, f(c)=a, and f(b)=d, f(d)=b, and also some other mapping such that when typing "ab" we get "ba"? Let's test: If f(a)=c, then typing a gives c. To get first character b, we need c = b, so c=b. So f(a)=b. Similarly, typing b must give a, so f(b)=a. So indeed a and b must be swapped. So forced.
Thus no alternative.
Now, is there any subtlety with multiple occurrences of the same pair? Already covered.
Now, what about the case where s and t contain letters that map in a way that seems consistent but leads to a key being involved in two swaps indirectly? For example, consider s="abc", t="bca". Let's process:
i0: a->b: f[a]=b, f[b]=a.
i1: b->c: f[b] currently a, conflict (needs to be c) -> impossible. So no solution. Indeed, if we try to find an involution: a->b, b->c, c->a would be a 3-cycle, not allowed. So impossible.
Now, consider s="abc", t="cab". i0: a->c: f[a]=c, f[c]=a. i1: b->a: f[b]=a? But f[a] is c, so for involution we need f[b]=a and then f[a]=b? Actually from b->a we set f[b]=a, f[a]=b? Wait processing: i1: b->a => set f[b]=a, and f[a]=b. But f[a] is already c from i0 => conflict. So impossible.
Now, consider s="abca", t="bacb". Let's see: i0: a->b: f[a]=b, f[b]=a. i1: b->a: consistent. i2: c->c: f[c]=c. i3: a->b: consistent. So mapping: a<->b, c fixed. Works. So output (a,b). Good.
Now, we should consider if there is any scenario where the mapping we derive from immediate propagation might be incomplete because we need to consider that some letters could be swapped with others not appearing? For example, suppose s contains letter a, and t contains b, but b does not appear in s anywhere else. Our algorithm forces f(a)=b and f(b)=a. That's fine. But could there be an alternative where a is swapped with some other letter x, and x is swapped with a, but then typing a yields x, but we need it to yield b. So x must be b. So forced.
But what about letters that appear only in t? They are forced as above.
Now, think about the case where a letter appears in s but not in t, and also appears in s at positions where t equals itself? Actually if a appears in s and never appears in t, then all occurrences of a in s must map to something else? But t would contain the images. So if a appears in s and never in t, then for each occurrence s[i]=a, we have t[i]=some letter b_i. If a maps to some fixed b (since f is a function), all occurrences must map to same b. So b appears in t. So a will appear in t if there is some occurrence mapping to a? Not necessarily. Actually if a maps to b, then a's image is b, so a does not appear as output unless some other letter maps to a. So a might not appear in t. That's okay. So our algorithm can handle that.
Now, is there any scenario where the mapping derived from constraints is consistent as a function but violates the "each key must occur in pairs at most once" because a letter appears as a fixed point but also as part of a swap? That would be conflict as we handle (f[a]=a then later f[a]=b). So fine.
Now, let's double-check the case where we have s[i]=a, t[i]=b, and also s[j]=b, t[j]=a. That's consistent and we set f[a]=b, f[b]=a. Good.
Now, consider if we have a situation where we have s[i]=a, t[i]=a (so f[a]=a) and also s[j]=a, t[j]=a again; no conflict.
Now, what about letters that appear only in t as result of a mapping, but also appear in s as a source of another mapping? That's fine.
Now, we need to output the swap pairs. One nuance: The problem says: "All printed letters must be distinct." So we cannot output a pair like (a,a). That's not a swap anyway.
Now, check if there could be a scenario where the mapping contains a fixed point that we might inadvertently output as a swap? We'll only output when a != f[a] and we ensure we output each pair once.
Implementation steps:
- Read two strings s, t (maybe using input().strip())
- n = len(s)
- Initialize f = [-1] * 26
- For i in range(n):
a = ord(s[i]) - 97
b = ord(t[i]) - 97
if a == b:
if f[a] == -1:
f[a] = a
elif f[a] != a:
print(-1); return
else:
# set f[a]=b
if f[a] == -1:
f[a] = b
elif f[a] != b:
print(-1); return
# set f[b]=a
if f[b] == -1:
f[b] = a
elif f[b] != a:
print(-1); return
After loop, we have mapping. But we might also need to check for any letters that have f[letter] defined but not satisfying f[f[letter]] == letter? Possibly if some bug: but we set both sides. However, consider a scenario where we set f[a]=b and f[b]=a, but later we might set f[a] to something else due to another constraint? That would conflict. So after loop, it should be consistent.
Nevertheless, it's safe to verify for each letter i where f[i] != -1: if f[i] != i and f[f[i]] != i: then it's inconsistent. But our algorithm ensures that, but we can add a check to be safe.
Now, collect pairs: visited = [False]*26. pairs = [].
For i in range(26):
if f[i] != -1 and f[i] != i and not visited[i]:
j = f[i]
if j < 0 or j >= 26: continue (shouldn't happen)
pairs.append((chr(i+97), chr(j+97))) # order can be any
visited[i] = visited[j] = True
But careful: There might be a case where f[i] != i, but f[f[i]] != i because of inconsistency? Already we check earlier; but just in case, we can ensure i < j to avoid duplicate, but using visited works.
Now, output k = len(pairs)
print(k)
for p in pairs: print(p[0], p[1])
Edge case: if f[i] is defined but i is not visited and f[i]!=i, we output pair and mark both. Since mapping is symmetric, it's fine.
Now, test with Example 1: yields 3 pairs.
Now, test with custom: s="ab", t="ba" => mapping: f[a]=b, f[b]=a. visited a->b, output (a,b). Good.
Now, test s = "a", t="b": f[a]=b, f[b]=a => pair (a,b). Good.
Now, test s = "ab", t="ab": mapping: all fixed. No pairs. Output 0.
Now, test s = "ab", t="ac": conflict -> -1.
Now, test s = "abc", t = "acb": we got f[a]=a, f[b]=c, f[c]=b => pairs: (b,c). Good.
Now, test s = "aa", t="bb": i0: a->b => f[a]=b, f[b]=a. i1: a->b again, consistent. So mapping: a<->b. So output (a,b). Is that valid? Let's think: typing "aa": first a yields b, second a yields b => "bb". So yes. So pair (a,b). Good.
Now, test s = "ab", t="aa": conflict as earlier.
Now, test s = "ab", t="bb": i0: a->b => f[a]=b, f[b]=a. i1: b->b? Actually s[1]=b, t[1]=b => fixed b? But f[b] is already a from i0, so conflict. So -1.
Now, test s = "ab", t="cc": i0: a->c => f[a]=c, f[c]=a. i1: b->c => f[b]=c? But f[c] is already a, and we need f[b]=c and also f[c]=b? Actually processing i1: b->c: set f[b]=c, f[c]=b. But f[c] is already a, conflict. So -1.
Now, test a case where multiple letters map to same target? Already conflict.
Now, test a case where mapping has a fixed point but also appears as target of another mapping? Already conflict.
Now, consider a case where there is a conflict only after processing all? Our algorithm detects on the fly.
Now, complexity O(n+alphabet) trivial.
Thus solution is straightforward.
But wait, let's re-read the problem statement: "Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be." This description might be interpreted differently: maybe Santa only suspects that some pairs of keys are swapped, but he does not suspect that any key is moved to a third location. That is exactly what we used.
The problem also says: "Each key must occur in pairs at most once." So we must not output duplicate letters.
Now, what about the possibility that there is a solution but our mapping includes a letter that maps to itself, but that letter also appears as part of a swap? That would be conflict.
Now, consider if s and t have different sets of letters? That's okay.
Now, we should be careful about the case where f[a] = b, but we never set f[b] because b never appears? Actually we always set f[b] when processing a->b. So f[b] gets set. So b appears in mapping. So all letters that appear as t in mismatched positions will have mapping defined.
Now, what about letters that appear only as t in equality positions? That is s[i]==t[i]=b, so b appears as s[i] as well because equal. So it's defined.
Now, what about letters that never appear at all? They are -1.
Now, output: we only output pairs for letters that are swapped. So if a letter is fixed, we don't output.
Now, check example 2: all fixed -> output 0.
Now, we must ensure we handle the case where the mapping is consistent but we have a letter that is swapped with itself? Not possible.
Now, think about the case where s and t are such that there is a solution but the mapping derived by our algorithm might have f[a] = b and f[b] = a, but also a letter c such that f[c] = c, all good.
Now, is there any scenario where we need to output a swap for a letter that is fixed? No.
Now, potential pitfalls:
-
When processing a==b, we set f[a]=a. But what if f[a] was already set to a? That's fine.
-
But what if f[a] was already set to something else (like b)? Conflict.
-
When processing a!=b, we set f[a]=b and f[b]=a. But what if f[a] was already set to b? That's fine. And f[b] already set to a? fine.
-
But what if f[a] was set to a (i.e., fixed) from earlier? That would conflict because we need f[a]=b.
-
What about if f[b] was set to b (fixed)? Conflict.
Now, what if we have a situation where f[a] is set to b, and later we encounter a position where a==b? That would be a conflict because it would require f[a]=a.
Thus algorithm catches.
Now, after building mapping, we must output the swaps. But note: The mapping may include letters that are fixed (f[letter]=letter). We ignore them. The pairs are those with f[letter] != letter.
But we must ensure that we don't output a pair like (a,b) and also (b,a). Using visited prevents that.
Now, confirm that our algorithm does not produce any conflict for valid cases.
Now, but there might be a scenario where the mapping we built is consistent as a function, but the actual physical swapping might be impossible because of something like: a letter appears as both source and target in a way that forms a chain? But our constraints guarantee it's an involution.
Now, what about letters that appear only as t in mismatched positions? We set f[b]=a. So b is mapped to a, and a is mapped to b. So b appears in a swap pair. Good.
Now, is there any scenario where the mapping is consistent but we might have a letter that maps to itself but also appears as target for another mapping? That would be caught.
Thus solution appears correct.
But wait, there is an interesting nuance: The problem says: "Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be." This description might be interpreted as: For each key, either it is correct, or it is swapped with exactly one other key, and that other key is at the first key's correct position. That is exactly an involution. However, it also says: "Each key must occur in pairs at most once." That's the same.
Now, is there any possibility that Santa might have swapped more than two keys in a cycle? No, because it says "pairs of keys took each other's place." So only pairwise swaps.
Thus the model is correct.
Now, confirm with a more complex case: s = "abcde", t = "badcf". Let's process:
i0: a->b => f[a]=b, f[b]=a.
i1: b->a => consistent.
i2: c->d => f[c]=d, f[d]=c.
i3: d->c => consistent.
i4: e->f => f[e]=f, f[f]=e.
So three swaps: (a,b), (c,d), (e,f). Works.
Now, check a case where a letter appears in multiple swaps indirectly? Already conflict.
Now, what about case where s = "ab", t = "bc"? i0: a->b => f[a]=b, f[b]=a. i1: b->c => conflict because f[b] is a, not c. So -1.
Now, all seems consistent.
Thus implementation is straightforward.
But before finalizing, let's think about possible alternative interpretations: Could it be that Santa only swapped some keys, but not necessarily that every key is either correct or swapped exactly with another? The phrase "each key is either on its place, or on the place of another key, which is located exactly where the first key should be" suggests exactly that. So it's involution.
Now, what about if a key is swapped with another, but that other key is also swapped with a third? That would form a cycle of length >2, which would not satisfy the description because then the first key is not directly at the place of the key that is at its place? Actually consider three keys: A at B's place, B at C's place, C at A's place. Then A is not at its place; it is at B's place. The key that is at A's place is C. So A is at B, B at C, C at A. The description says "each key is either on its place, or on the place of another key, which is located exactly where the first key should be." For key A, it is on B's place. The key that is at A's place is C. So the "another key" that is located exactly where A should be is C, but A is not on the place of C? Actually "on the place of another key, which is located exactly where the first key should be." It says: each key is either on its place, or on the place of another key, which is located exactly where the first key should be. That seems to indicate that if key K is not in its place, it is in the place of some key L, and that key L is exactly at K's place. So K and L swap places. So cycles of length >2 are excluded. So our model is correct.
Thus solution is simple.
Now, let's produce final solution.
Implementation in Python:
def solve():
import sys
s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()
n = len(s)
# f array: -1 unknown, else mapping letter index (0-25)
f = [-1]*26
for i in range(n):
a = ord(s[i]) - 97
b = ord(t[i]) - 97
if a == b:
if f[a] == -1:
f[a] = a
elif f[a] != a:
print(-1)
return
else:
# set f[a] = b
if f[a] == -1:
f[a] = b
elif f[a] != b:
print(-1)
return
# set f[b] = a
if f[b] == -1:
f[b] = a
elif f[b] != a:
print(-1)
return
# additional check: for all i where f[i]!=-1, f[f[i]] should be i (if f[i]!=i)
# but our construction ensures; optional:
for i in range(26):
if f[i] != -1 and f[i] != i:
if f[f[i]] != i:
print(-1)
return
# collect pairs
visited = [False]*26
pairs = []
for i in range(26):
if f[i] != -1 and f[i] != i and not visited[i]:
j = f[i]
# sanity: j should be within 0..25 and f[j]==i
if j < 0 or j >= 26 or f[j] != i:
# should not happen if check above passed
continue
pairs.append((chr(i+97), chr(j+97)))
visited[i] = True
visited[j] = True
# output
print(len(pairs))
for a,b in pairs:
print(a, b)
But wait: There is a nuance: In the equality case, we set f[a] = a. But what if a later appears as a target in a mismatched pair? For example: s[i]=a, t[i]=a (set f[a]=a). Later, we see s[j]=b, t[j]=a (b!=a). Then we will try to set f[a]=b? Actually processing b->a: we set f[b]=a and f[a]=b. But f[a] is already a, conflict. So caught. Good.
Now, what about case where we have equality for a, but later we have a mismatched pair where a is the source? That also conflicts.
Thus good.
But what about case where we have a mismatched pair a->b, setting f[a]=b, f[b]=a. Later, we have equality for b? That would require f[b]=b, but already a, conflict. So caught.
Thus all good.
Now, check a scenario where we have a mismatched pair a->b, but later we have another mismatched pair b->a? That's consistent.
Now, we should test a few random cases to ensure no oversight.
Let's write a small brute-force for small n and alphabet to verify that the condition is necessary and sufficient. But in reasoning, it's fine.
But I'll do mental verification with some tricky case: s = "ab", t = "ba". Our algorithm returns pair (a,b). That is correct.
Now, s = "aba", t = "bab". i0: a->b: f[a]=b, f[b]=a. i1: b->a: consistent. i2: a->b: consistent. So mapping: a<->b. Output (a,b). Check: typing "aba": a->b, b->a, a->b => "bab". Yes.
Now, s = "aba", t = "aba". i0: a->a: set f[a]=a. i1: b->b: set f[b]=b. i2: a->a: consistent. Output 0. Check: identity works.
Now, s = "abc", t = "abc". identity.
Now, s = "abc", t = "abd". i0: a->a: set f[a]=a. i1: b->b: set f[b]=b. i2: c->d: set f[c]=d, f[d]=c. So mapping: a fixed, b fixed, c<->d. Output (c,d). Check: typing "abc": a->a, b->b, c->d => "abd". Yes. But note that d appears only as target; but that's okay.
Now, s = "abc", t = "acd". i0: a->a: f[a]=a. i1: b->c: set f[b]=c, f[c]=b. i2: c->d: but f[c] is already b, conflict (need f[c]=d). So impossible. Indeed, if we try to satisfy, we would need f(c)=b and f(c)=d, impossible.
Thus correct.
Now, think about a scenario where we have s = "ab", t = "ba". Could there be a solution where we swap a with c and c with b? That would be a cycle of length 3? Actually if we swap a with c and c with b, that would mean a<->c and c<->b? That's not a disjoint swap; a key cannot be in two swaps. So not allowed. So only a<->b works.
Now, everything seems fine.
But wait, the problem statement: "Each key must occur in pairs at most once." In the output, we must list the pairs. The mapping we output should be such that each letter appears at most once. Our pairs satisfy that. But what if the forced mapping includes a letter that is swapped but appears only once in the mapping? That's fine.
Now, edge case: mapping may contain a letter that is swapped but also that letter appears as fixed? Not possible.
Now, consider a scenario where the mapping we build from constraints is consistent, but there is a letter that maps to itself (fixed) but also appears in a swap pair? Already conflict.
Now, I think solution is done.
Now, let's consider if there is any scenario where the constraints are consistent but the mapping is not an involution because we didn't enforce f(f(a)) = a for letters that are not directly constrained? But we did enforce for each mismatched pair we set both directions. However, what about a scenario where we have a letter that is never directly encountered as source in any mismatched pair, but appears as target? In our else branch, we set both directions. So it's covered.
Thus all good.
One more nuance: In the equality case, we only set the mapping for the letter itself. But what if that letter later appears as target in a mismatched pair? That conflict we catch. But what if that letter appears as source in a mismatched pair? Conflict. So fine.
Now, is there any scenario where we need to consider that a letter might be swapped with another letter that never appears? For example, s = "a", t = "a". Identity works. Could there be a scenario where s = "a", t = "a" but the keyboard actually has a swap a<->b, but because we never press b, we still get a? If a and b are swapped, then pressing a yields b, not a. So that would not produce a. So not possible. So identity forced.
Now, consider s = "a", t = "b". Then forced a<->b. So b appears in mapping. So letters that are swapped must appear in either s or t. So any swap must involve letters that appear. So our mapping covers all swaps.
Thus solution stands.
Now, complexity: O(n + 26) time, O(26) memory.
Now, potential pitfalls: reading input, there might be trailing newlines; strip is fine.
Now, I think we can finalize.
But before finalizing, let's consider if there is any possibility of an alternative interpretation: maybe Santa typed the pattern looking only at the keyboard, meaning he typed based on the labels he saw? Actually typical keyboard swapping problems: You have a keyboard where some keys are swapped. When you look at the keyboard, you see the labels, so you press the key that has the desired letter printed on it. But here, Santa typed his favorite pattern looking only at his keyboard. That could mean he was looking at the keyboard to see which keys to press, i.e., he pressed the keys that have the letters of his pattern as printed on the key caps. But the pattern is a string he wants to type, but he looks at the keyboard to find the keys. In a typical scenario: If the keyboard has swapped keys, the physical labels are still the same (the letters on the keycaps). When you look at the keyboard, you see the letters. You want to type "h", you press the key that has "h" printed on it. But if keys are swapped, that key might be in a different location. Actually the keys themselves have printed letters. Swapping keys means exchanging the keycaps, so the letter on the keycap moves. So if you press the key that has "h" printed on it, you'll get whatever the underlying switch is programmed to? But in typical keyboard, the keycap's letter indicates the key's function; if you swap keycaps, the key you press (the physical position) is determined by the location, not the label. However, if you look at the keyboard, you see the labels; you would press the key that has the label of the desired character. But that key is in a particular physical position. That physical position corresponds to some character in the computer's mapping. Typically, the computer registers a key based on its scancode (position), not the label. So swapping keycaps does not change which character is produced when you press a given physical key; it only changes the label you see. Therefore, if you look at the keyboard and press the key that shows 'h', you are actually pressing the physical key where that keycap is currently located. That physical key might originally have been some other letter's position. So the effect is the opposite of what we considered? Let's analyze carefully, because this is a common source of confusion in keyboard swap problems.
We need to interpret the scenario correctly:
- Santa disassembled his keyboard to clean it, then returned all the keys back, but some pairs of keys took each other's place. So the physical keycaps (with letters printed) have been swapped. The keyboard electronics (the switches) are fixed to positions. When you press a physical key at a certain location, it sends a signal corresponding to that location, regardless of the keycap label. So the character produced is determined by the location (the key's position). The keycap's label indicates what character we expect to be produced when pressing that key if the keyboard is correctly assembled. After swapping keycaps, the labels are misplaced.
Now, Santa typed his favorite pattern looking only at his keyboard. That means he looked at the keycaps (the labels) to decide which keys to press. So to type a letter, he finds the keycap that has that letter printed on it, and presses it. Because the keycaps might be swapped, the location he presses corresponds to the physical key where that keycap currently resides, which might be the original location of some other letter.
Thus, let’s formalize:
Let the set of keys be identified by their intended letters (the letters that should be on them). Initially, key labeled A is at position A (the position that produces character A when pressed). After swapping, some keycaps have moved. Define a permutation p on the letters: p(A) is the current location (position) of the keycap labeled A. Since swapping pairs, p is an involution? Actually if we swap keycaps A and B, then the keycap labeled A goes to position B (the physical key that originally produced B), and the keycap labeled B goes to position A. So p(A)=B, p(B)=A. For other letters, p(C)=C. So p is an involution (p(p(A)) = A). Now, when Santa wants to type a letter X (from his pattern), he looks at the keyboard and finds the keycap with X printed on it. That keycap is at position p(X). He presses that position. The character produced by pressing position p(X) is whatever that position is mapped to by the computer, which is the original letter of that position. That is, position Y (physical key) always produces character Y. So the typed character when he intends X is the character corresponding to the position he presses, which is p(X). So typed character = position = p(X). Thus t = p(s[i]) for each i.
Now earlier, we had a different mapping: we defined f such that typed = f(s[i]). So f = p. And p is an involution. So it's the same mapping: f is the permutation of keycaps, mapping intended letter to typed letter. So our earlier reasoning is consistent.
But wait, earlier we thought f is the mapping from intended to typed, and we argued that if a and b are swapped, then pressing a yields b, pressing b yields a. That matches p: p(a)=b, p(b)=a. So indeed same.
Thus our interpretation is correct.
Now, check the phrase: "each key is either on its place, or on the place of another key, which is located exactly where the first key should be." That describes the keycap positions: key A is either at its own place (p(A)=A) or at the place of another key B, and that key B is at A's place (so p(B)=A). This exactly says p is an involution.
Thus our model is correct.
Now, let's double-check with an example: Suppose keys A and B are swapped. Then p(A)=B, p(B)=A. So when Santa wants to type A, he looks at keycap A, which is at position B, so he presses position B, and B is typed. So typed = B. Similarly for B gives A. So f(A)=B, f(B)=A.
Now, if Santa typed his favorite pattern s and got t, then t[i] = p(s[i]). So we need to find p (an involution) such that for all i, p(s[i]) = t[i]. That's exactly what we solved.
Thus the solution is solid.
Now, implementation details: Input may have multiple test cases? The problem statement says "The input consists of only two strings s and t". So just one case.
Now, output format: first line integer k, then k lines with two space-separated letters. Letters can be printed as characters. Ensure we don't have trailing spaces.
Now, all good.
But wait, there is a nuance: The problem says "Each key must occur in pairs at most once." That is a condition on the output; we must output a set of pairs where each letter appears at most once. Our output ensures that.
Now, consider a scenario where the mapping includes a swap pair, but one of the letters in the pair is also fixed? That would be contradictory.
Now, also consider the scenario where s and t produce a mapping where a letter maps to itself (fixed) but also is involved in a swap because of some other constraint? Already conflict.
Now, I'll also think about the possibility of a solution that requires swapping more than the forced pairs? For letters not appearing, we could add extra swaps, but that would add letters that appear in the output. But the problem says "All printed letters must be distinct." That would be violated if we added extra swaps involving letters that already appear in forced swaps? Not if they are new letters. But if we add extra swaps among letters not appearing, those letters would appear in the output. The problem doesn't forbid that, but the output would include letters that are not necessary. However, the problem says "Determine which pairs of keys could be mixed." It might be interpreted as we need to output exactly the pairs that are mixed, not extra ones. Since we can output any valid answer, both minimal and non-minimal are acceptable. But we must ensure that the letters we output are distinct (no duplicates). So if we add extra swaps on new letters, that's okay as long as they are distinct from each other and from existing. But our algorithm outputs only forced swaps (the ones that appear in mapping). Could there be a case where forced swaps are not enough to be a valid solution? They are enough because they satisfy t = p(s). But if there are letters not appearing, we could leave them fixed. That's a valid keyboard state: only those forced swaps are present. So it's valid.
Now, note: The mapping we constructed includes all letters that appear either in s or t, and assigns them either fixed or swapped. For letters not appearing, we don't assign, but we can assume they are fixed. So the keyboard with only those swaps is valid.
Thus output is correct.
Now, a subtle point: What about a letter that appears in s and also appears as t, but not necessarily in a consistent way? Already conflict.
Now, think about a scenario where s and t are such that for some letter a, we have both a->b and a->c? Conflict.
Now, also think about scenario where s and t have same length but different sets; fine.
Now, let's test a more complex case that might reveal a hidden requirement: Suppose s = "ab", t = "ba". Our mapping gives swap (a,b). That's fine. But suppose also there is a letter c that appears nowhere. Could we have a solution where we swap a with c and c with b? That would be a cycle of length 3? Actually that would be a->c, c->b, b->a? That would be a 3-cycle, which is not allowed because p must be an involution (only swaps). So not allowed. So only a<->b works.
Now, think about a scenario where there is a solution that is not forced due to the ability to choose different swaps for letters that appear multiple times? For example, consider s = "aa", t = "bb". Our algorithm: i0: a->b => f[a]=b, f[b]=a. i1: a->b consistent. So swap (a,b). Could there be another involution that yields the same mapping? For example, could we have f[a]=c, f[c]=a, and f[b]=d, f[d]=b, and then also some mapping such that when we type a we get b? That would require f(a)=b, so c must be b. So no.
Thus forced.
Now, I'm confident.
Now, let's check for potential pitfalls in code:
- We need to convert letters to indices 0-25. Ensure ord conversion is correct.
- When we set f[a] = a for equality case, we store the index a, not the character.
- When checking f[a] != a, we need to ensure we compare ints.
Now, potential bug: In the equality case, if f[a] is -1, we set f[a]=a. But if later we encounter a mismatched pair a->b, we will check f[a] and conflict because f[a]==a != b. That's correct.
But what about a scenario where we encounter equality after a mismatched pair? For example, first a->b (set f[a]=b, f[b]=a). Later we see a->a (equality). That will check f[a]==b, which is != a, so conflict. Good.
Now, what about scenario where we first have equality for a, then later we have a mismatched pair b->a. That will attempt to set f[a]=b (since in else branch we set f[t[i]]=s[i] when t[i]=a, s[i]=b). f[a] is a (from equality), conflict. Good.
Now, what about scenario where we have equality for a, then later we have mismatched pair a->b, conflict.
Thus all conflicts caught.
Now, consider scenario where we have mismatched pair a->b, but later we have mismatched pair a->b again (duplicate). That's fine.
Now, consider scenario where we have mismatched pair a->b, and later mismatched pair b->a. That's fine.
Now, after processing all, we might have a situation where f[a]=b, f[b]=a, but also maybe f[a] is set to b, and f[b] is set to a. All good.
Now, check additional consistency: In the loop, for each mismatched pair we set both directions. But what if we encounter the mismatched pair a->b after already having set f[a]=b from previous, and f[b]=a from previous? Then both conditions will pass because f[a]==b and f[b]==a. That's fine.
Now, one more nuance: Could there be a scenario where the mapping derived is consistent but violates the rule that each key occurs in at most one pair because of a letter that appears in two pairs? For example, suppose we have a->b and b->c? That would create a conflict. But our algorithm would catch because when processing b->c, f[b] is already a, not c. So conflict.
Thus fine.
Now, after building mapping, we need to output pairs. We'll iterate over i from 0 to 25. For each i, if f[i]!=-1 and f[i]!=i and not visited[i], we output. We'll mark both visited.
But careful: There might be a case where f[i] is defined but f[i] = j, and f[j] is defined but not equal to i? That would be inconsistent. But our additional check can catch that. We'll include a check for safety.
Now, we might also want to ensure that we only output letters that appear in the mapping and are swapped. But what about letters that are fixed (f[i]=i)? They should not appear in output. So we ignore them.
Now, output order: It says "You are free to choose the order of the pairs and the order of keys in a pair." So any order is fine.
Now, about the initial reading: The input consists of two strings, possibly on separate lines. We'll use input().strip() for both.
Now, possible issue: The strings may contain uppercase? The problem says lowercase English letters. So okay.
Now, edge case: n up to 1000, so reading is fine.
Now, the solution is ready.
But wait, there is a nuance: In the equality case, we set f[a] = a. But what if f[a] was already set to a? That's fine. But what if f[a] was already set to b (from a previous mismatched) and later we see a->a? Then conflict as discussed.
Now, everything seems fine.
Now, let's test with the given examples programmatically.
Example 1:
s = "helloworld"
t = "ehoolwlroz"
Our algorithm should produce 3 pairs.
Example 2: identity -> 0.
Example 3: -> -1.
Now, implement and test mentally.
Now, consider a case where we have s and t such that there is a conflict that only appears after full propagation? Our algorithm processes sequentially, and when it sets both directions, it propagates constraints immediately. But is it possible that a conflict arises from transitive closure that is not immediately apparent? For example, consider s = "ab", t = "bc". Process i0: a->b: set f[a]=b, f[b]=a. i1: b->c: we check f[b] is a, need f[b]=c => conflict. So immediate.
Now, consider s = "ab", t = "ca". i0: a->c: f[a]=c, f[c]=a. i1: b->a: set f[b]=a, f[a]=b? f[a] is c, conflict. So immediate.
Now, consider a longer chain: s="abc", t="bca"? Already conflict immediate.
Now, consider case where we have s="ab", t="ba" and also s="c", t="c". That's fine.
Now, so no hidden transitive conflict.
Thus solution is straightforward.
Now, let's think about if there could be a scenario where the mapping is consistent but some letter is forced to be both fixed and swapped due to different occurrences? Already conflict.
Now, confirm that the mapping we output indeed fixes the keyboard: That is, if we swap the pairs we output, then typing s will produce t. Yes.
Now, one more nuance: The problem says "Each key must occur in pairs at most once." That is a condition on the output, not necessarily on the solution? But it's inherent.
Now, finalize.
But before finalizing, let's consider if there could be a scenario where our algorithm produces a mapping that has a letter mapped to a different letter, but that different letter maps to a third, creating a chain? That would mean inconsistency because we would have set f[b] = a from the first pair, but if later we set f[b] = c from another, conflict. So not possible.
Thus solution is correct.
Now, let's write the final answer.
Potential improvements: Instead of using -1, we could use None or -1. But careful: We need to differentiate between unassigned and assigned to itself. Using -1 for unassigned and values 0-25 for assigned. But if a letter is assigned to itself, it's value = index, which is 0-25. So we can check.
Now, one more check: In the equality case, if f[a] is -1, we set f[a] = a. That's fine. But what if later we encounter a mismatched pair where a is the source and b is something else? Then we will attempt to set f[a] = b, but f[a] is a, conflict. Good.
Now, code.
Implementation in Python:
def solve():
import sys
s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()
# maybe there are extra whitespace lines; but we assume exactly two lines.
n = len(s)
f = [-1] * 26
for i in range(n):
a = ord(s[i]) - 97
b = ord(t[i]) - 97
if a == b:
if f[a] == -1:
f[a] = a
elif f[a] != a:
print(-1)
return
else:
if f[a] == -1:
f[a] = b
elif f[a] != b:
print(-1)
return
if f[b] == -1:
f[b] = a
elif f[b] != a:
print(-1)
return
# optional consistency check
for i in range(26):
if f[i] != -1 and f[i] != i:
if f[f[i]] != i:
print(-1)
return
visited = [False] * 26
pairs = []
for i in range(26):
if f[i] != -1 and f[i] != i and not visited[i]:
j = f[i]
# ensure j within range and not visited (should be)
if 0 <= j < 26 and not visited[j]:
pairs.append((chr(i+97), chr(j+97)))
visited[i] = True
visited[j] = True
print(len(pairs))
for a, b in pairs:
print(a, b)
Now, test with provided examples.
Example 1:
s="helloworld", t="ehoolwlroz". The loop as earlier yields pairs. Should output 3 and pairs. Our code will output (h,e), (l,o), (d,z) if order of iteration yields those first. Actually iteration from 0..25: a=0('a')? f['a']? Not set? Let's see mapping: we have letters: h(7), e(4), l(11), o(14), w(22), r(17), d(3), z(25). f[7]=4, f[4]=7; f[11]=14, f[14]=11; f[22]=22; f[17]=17; f[3]=25, f[25]=3. So when iterating i from 0: i=3 (d) -> f[3]=25 !=3 and not visited, we will output (d, z) because j=25, and mark both visited. Then i=4 (e): f[4]=7 but visited[4]? Not yet? Actually visited[4]? e is not visited because we haven't visited i=4 yet. But we will output (e, h)? But we need to check: when i=4, f[4]=7 and not visited[4], we will output (e, h). However, note that h (i=7) is not visited yet? But we already visited d and z, not h. So we will output (e, h) as a pair. Then i=7 later will be visited already? Actually after outputting (e, h), we mark visited[4] and visited[7] = True. So later i=7 is visited, skip. i=11: f[11]=14, not visited, output (l, o). So pairs output order: (d,z), (e,h), (l,o). That's valid; letters are distinct across pairs? d,z,e,h,l,o are all distinct, yes. So output is fine. The example output had order (h e), (l o), (d z). Any order is allowed. So okay.
Example 2: identity, all f[i] either -1 or equal to i. So no pairs. Output 0.
Example 3: conflict, output -1.
Thus matches.
Now, consider a tricky case: s = "ab", t = "ab". f[a]=a, f[b]=b. Output 0.
Now, s = "ab", t = "ba". Output 1 pair.
Now, test s = "aa", t = "bb": Output 1 pair (a,b). Our algorithm: i0: a->b set f[a]=b, f[b]=a; i1: a->b check f[a]==b ok, f[b]==a ok. So pairs: (a,b). Good.
Now, consider s = "abc", t = "acb". i0: a->a set f[a]=a; i1: b->c set f[b]=c, f[c]=b; i2: c->b check f[c]==b ok, f[b]==c ok. So pairs: (b,c). Output 1.
Now, consider s = "abca", t = "bacb". i0: a->b set f[a]=b, f[b]=a; i1: b->a ok; i2: c->c set f[c]=c; i3: a->b ok. So pairs: (a,b). Output 1.
All good.
Now, think about input where s and t contain letters not in alphabet? Not possible.
Thus final solution is ready.
Now, one more thought: Could there be a scenario where the mapping is consistent but the number of pairs we output might be zero even though there are some swaps? No, if there is a swap, we will output it.
Now, any scenario where the mapping has a letter that maps to itself but also appears as a target of another mapping? Already conflict.
Now, about memory: fine.
Now, we must ensure that we don't accidentally output a pair where the two letters are the same (a,a). That can't happen because we check f[i]!=i.
Now, output formatting: print each pair as two characters separated by space. In Python, print(a, b) will print with space. That's fine.
Now, handle possible extra newline at end? Not needed.
Now, I'll produce final answer.
But I recall there might be a Codeforces problem similar to this: "Santa Claus and Keyboard" or something. Actually I think this is from Codeforces Round? But anyway.
Now, let's produce final solution in the answer.
Before final, I want to double-check if there is any scenario where the mapping is not uniquely determined but our algorithm might incorrectly output a pair because it sets f[a]=b and f[b]=a but later we find that a could also be fixed if we choose a different configuration? But we argued it's forced.
Consider: s = "a", t = "a". Our algorithm sets f[a]=a. Could there be an alternative configuration where a is swapped with some other letter b, but then when we type a we get b, not a. So to get a, we would need that pressing a yields a, so a must be fixed. So forced.
Consider s = "ab", t = "ba". Could there be an alternative where a is swapped with c, and b is swapped with d, and also c is swapped with b? That would be a 3-cycle? Not allowed.
Thus forced.
Now, consider scenario with multiple possible involutions? For example, suppose s = "ab", t = "ab". One could have no swaps, or could have swaps among letters that never appear? But those swaps would not affect typing, so they could exist. But then the mapping f would have f(a)=a, f(b)=b, but also f(c)=d, f(d)=c. That would still satisfy that for s letters, f(s[i]) = t[i] because s letters are a and b, and f(a)=a, f(b)=b. So this is a valid keyboard state. In such a case, there are multiple valid sets of swaps. Our algorithm outputs only the forced swaps (none). That's a valid answer (k=0). The problem says "print any of them." So it's acceptable. However, note that they require "All printed letters must be distinct." In k=0, no letters printed, so fine.
Now, but could there be a case where we need to output some swaps even though s and t are identical? Not necessary.
Now, think about a scenario where s and t are identical but there is a forced swap? No, because if there is a swap (a,b) then for any occurrence of a in s, t would be b, so if s contains a, t must contain b. So if s=t, no forced swaps.
Thus fine.
Now, overall solution done.
One more nuance: The problem might be from a contest where they expect the output to be in a specific format: maybe the letters should be lowercase and separated by a space, and each pair on a new line. That's what we do.
Now, answer.
But to be thorough, let's test with a random brute-force for small n and small alphabet (e.g., 4 letters) to see if there is any case where our algorithm says impossible but actually there is a solution, or vice versa. But we can reason.
We'll do a quick mental enumeration: Suppose alphabet = {a,b,c}. Consider all possible involutions p (with fixed points allowed). There are several: identity; (a b); (a c); (b c); (a b)(c) actually c fixed; etc. No 3-cycles. For each p, we can generate pairs (s,t) by taking any s and compute t = p(s). Then given such (s,t), our algorithm should find p. For any (s,t) not produced by any involution p, algorithm should say impossible. So correctness is equivalent to: The necessary and sufficient condition for existence of involution p satisfying t[i]=p(s[i]) for all i is exactly that there is no conflict in the constraints f(s[i])=t[i] and involution property. And our algorithm exactly checks those constraints. So it's correct.
Now, we can also think of it as building a graph where each letter is a node, and we add edges s[i] -> t[i] with the condition that each node has out-degree at most 1 (since f is a function) and if edge is a non-loop, then the reverse edge must exist. Our algorithm ensures that.
Now, it's correct.
Now, final answer.
But I'll also consider if there is any chance that we need to output the pairs in lexicographic order or something? Not required.
Thus final solution.
Now, I'll write the final message with the explanation and code. ```python
import sys
def solve() -> None:
s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()
n = len(s)
# f[i] = where key i moved to, -1 means unknown
f = [-1] * 26
for i in range(n):
a = ord(s[i]) - 97
b = ord(t[i]) - 97
if a == b:
# must be fixed
if f[a] == -1:
f[a] = a
elif f[a] != a:
print(-1)
return
else:
# set f[a] = b
if f[a] == -1:
f[a] = b
elif f[a] != b:
print(-1)
return
# involution forces f[b] = a
if f[b] == -1:
f[b] = a
elif f[b] != a:
print(-1)
return
# optional final consistency check (should never fail)
for i in range(26):
if f[i] != -1 and f[i] != i:
if f[f[i]] != i:
print(-1)
return
visited = [False] * 26
pairs = []
for i in range(26):
if f[i] != -1 and f[i] != i and not visited[i]:
j = f[i]
# j is always a valid index and unvisited because of symmetry
pairs.append((chr(i + 97), chr(j + 97)))
visited[i] = visited[j] = True
print(len(pairs))
for x, y in pairs:
print(x, y)
if name == "main":
solve()