We are given two strings a and b, length from 1 to 200,000, same length. Need to determine if they are equivalent according to the definition: equivalent if either they are equal, or if we split each into two halves (note: length must be even to split? The definition says: "if we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2" So splitting assumes length is even. If length is odd? Actually the definition says "two halves of the same size" which implies the string length is even. But note: The strings have length from 1 to 200,000, so they could be odd. However, the equivalence definition only provides the split case. For odd length, only the equal case applies. So we need to implement recursion/divide and conquer to test equivalence.
Given the length can be up to 200k, we need an efficient algorithm. The direct recursive approach could be O(n log n) if we cut at each step. But we need to be careful about comparing halves. We can implement a function equivalent(a, b) that works on substrings. Base case: if a == b return true. If length odd: return false unless equal. If length even: split a into a1, a2, b into b1, b2. Then check if (equivalent(a1,b1) and equivalent(a2,b2)) or (equivalent(a1,b2) and equivalent(a2,b1)).
But naive recursion with string copying would be O(n^2) due to substring copies. We need to avoid copying. Use indices: work on ranges in the original strings. So define function f(start_a, start_b, len). Then we can implement recursion with memoization? Possibly the recursion depth is O(log n). For each call, we might compute both possibilities. The worst-case complexity: T(n) = 4 T(n/2) + O(1) if we do both checks naively, which would be O(n^2). But we can optimize: If we compare the halves directly? Actually we can sort the strings? However we need to follow the equivalence property.
Observation: The equivalence definition is similar to "matching after possible swapping of halves". This is like checking if two strings are isomorphic under the operation of swapping children in a perfect binary tree representation. This is essentially checking if the strings are equal after recursively sorting each half? Let's think: For each substring, we can define a canonical form: sort the string in such a way: For even length, recursively compute canonical forms of two halves, then compare them lexicographically, and take the smaller as left and larger as right? Actually the equivalence condition: Two strings are equivalent if either they are equal or after splitting, either the halves correspond directly or crosswise. This is similar to determining if two strings are "shuffle equivalent" under this specific operation. We can define a normalized representation: For a given string, we can recursively transform it into the lexicographically smaller concatenation of its sorted halves? But careful: The equivalence allows swapping of halves based on equivalence of contents, not based on lexicographic order. But we can derive that two strings are equivalent if and only if their "signatures" are equal when we recursively sort the halves. Let's analyze.
Suppose we have a function f(s) that returns a canonical representation: If length is odd, just return s itself (since no further operation). If length is even, split into s1, s2, compute f(s1) and f(s2). Then compare f(s1) and f(s2) lexicographically. If f(s1) <= f(s2), return f(s1) + f(s2); else return f(s2) + f(s1). But is that sufficient? Actually, consider equivalence: Two strings are equivalent if you can rearrange the halves recursively. This canonical representation is similar to building a binary tree where at each node you can swap left and right children if needed. If we force the order such that left <= right lexicographically after canonicalization, then two strings are equivalent iff their canonical strings are equal. But is that always true? Let's test on simple examples. Suppose strings are "ab" and "ba". Length 2 even. Compute f("ab"): split "a","b": f("a")="a", f("b")="b". Since "a"<="b", canonical = "ab". For "ba": split "b","a": f("b")="b", f("a")="a". Compare "b" and "a": "a"<="b"? Actually we need to compare f(s1) and f(s2). For "ba", f(s1)="b", f(s2)="a". Since "a" <= "b", we would return f(s2)+f(s1)="ab". So both become "ab". So equivalent.
Consider "aa" and "aa". Both canonical "aa".
Now consider "aaba" and "abaa". Let's compute: For "aaba": length 4. Split "aa" and "ba". Compute f("aa"): length 2 even? Actually "aa" length 2. Split "a","a": f("a")="a", f("a")="a", compare equal, so canonical "aa". For "ba": length 2: split "b","a": f("b")="b", f("a")="a", compare "a"<="b" => canonical "ab". So we have f(s1)="aa", f(s2)="ab". Compare "aa" <= "ab"? yes, so canonical = "aa"+"ab" = "aaab". For "abaa": split "ab" and "aa". f("ab"): as above "ab"? Actually "ab": length 2: split "a","b": f("a")="a", f("b")="b", compare "a"<="b" => canonical "ab". f("aa") = "aa". Compare "aa" and "ab": "aa" <= "ab", so canonical = "aa"+"ab" = "aaab". So both canonical "aaab". Works.
Consider "aabb" and "abab". "aabb": split "aa","bb". f("aa")="aa", f("bb")="bb". Compare "aa" <= "bb"? yes => canonical "aabb". "abab": split "ab","ab". f("ab")="ab", f("ab")="ab". Compare "ab" <= "ab" => canonical "ab"+"ab" = "abab". So canonical strings "aabb" vs "abab", not equal. So not equivalent, matches expected.
Now consider more complex scenario: what if odd length? For odd length, no split, so canonical is the string itself. Two odd-length strings are equivalent only if they are equal. That matches definition.
But is it always sufficient? Suppose we have strings that are equivalent via multiple swaps, but the canonical representation that sorts halves lexicographically might produce the same string? The idea is that the equivalence relation partitions strings into equivalence classes. The operation at each node allows swapping left and right subtrees if the subtrees are equivalent? Wait: Actually the condition for swapping is that a1 equivalent to b2 and a2 equivalent to b1. That's exactly the condition for being able to swap the two halves. So at each level, we are allowed to swap the two halves if the contents are such that after swapping, the entire string becomes equivalent. This is akin to the equivalence relation generated by allowing swapping of halves recursively. So we can think of each string as a binary tree where leaves are characters, and internal nodes represent concatenation with the ability to swap children if the children's equivalence classes allow it. Then two strings are equivalent if the unordered trees (with unordered children) are isomorphic. So canonical representation can be obtained by sorting the children's canonical representations at each node (i.e., putting the smaller one first). Then two trees are isomorphic if and only if their canonical strings are equal. This is similar to constructing a canonical form for a rooted unordered tree. So yes, that approach should work.
But careful: The equivalence definition also includes case 1: they are equal. So base case: equal strings are equivalent. The recursion uses equivalence of halves. This exactly corresponds to unordered tree isomorphism. So the canonical representation idea works.
Now complexity: If we implement recursively building the canonical string for each substring, we could end up creating many strings. However total size of all canonical strings at each level? In typical approach for tree canonicalization, you can compute a hash or a normalized string. Since the final canonical string is the whole string after sorting children? Actually the canonical representation of a string s of length n is a string of length n (the same length). But we are constructing it recursively: For even length, we compute canonical representations of halves, then concatenate them in sorted order. So it's like we are sorting the halves at each step. This is similar to constructing the "sorted" version of the string under this recursive operation? But note that the canonical string we produce might not be the original string; it's a normalized form. The length remains n. So building the canonical string for the whole string will require O(n log n) time? Let's analyze.
If we compute f(s) for a string of length n, we recursively compute f on two halves, each returns a string of length n/2. Then we compare these two strings lexicographically to decide concatenation order. Comparing two strings of length n/2 could take O(n/2) in worst case. Then we return the concatenated string. So the recurrence: T(n) = 2T(n/2) + O(n) (for concatenation? Actually concatenation is just building a new string of length n, but that is O(n) anyway. But we also need to compare the two halves. So T(n) = 2T(n/2) + O(n) => T(n) = O(n log n). Since n up to 200k, O(n log n) is acceptable. However careful about memory: each recursion returns a new string, causing copying of entire substrings each time, leading to O(n log n) total memory allocation? Actually at each level, we produce strings of total size n for each node? Let's think: At the top level, we produce one string of length n. At the next level, we produce two strings of length n/2 each, total n. At the next, four strings of n/4 each, total n, and so on. So total memory allocated across recursion is O(n log n) if we keep them all simultaneously? But if we are just returning strings, and they are temporary, many will be deallocated after used. However each call returns a string that gets used by its parent. The parent will keep the two halves strings to concatenate. The concatenation creates a new string of combined length. Then the halves may be destroyed. So at any point, the recursion stack holds strings for the current path plus maybe siblings? Actually typical recursion: f(s) calls f(left) and f(right). It gets two strings L and R, then compares, then constructs result = (L <= R) ? L+R : R+L, then returns result. During the call of f(left), it will allocate a string for that subtree and then return it. After f(left) returns, we call f(right) and get its string. So at the moment when constructing result, we have both L and R present, plus we are about to create a new string of length n. So total memory usage for that call is O(L+R+n) = O(n) for that level? But L and R are from children; they still exist until we free them after constructing result. However after result is formed, the children strings can be destroyed (if using move semantics or by returning). However if recursion depth is log n, then the call stack holds strings of sizes that are decreasing as we go down? Actually each recursive call on the way down creates new strings? No, the call to f(s) will eventually call f(small) which returns a small string; that small string is stored in a local variable of the parent. The parent's local variables (L, R) will hold those strings while it constructs its own result. So at the deepest recursion, we have many strings? The memory allocated at any time is the sum of sizes of strings that are currently alive. In the recursion tree, we have one call at top active, but it has called f(left) and got L, then called f(right) and got R. While f(right) is being executed, f(left) has already returned and its string L is stored in the parent's local variable (but f(right) hasn't returned yet). But f(right) will allocate its own internal strings recursively. So there is overlapping: during the execution of f(right), the stack contains frames for the top call (holding L) and all frames for the recursive calls inside f(right). The frames of f(right) will allocate strings for subtrees of right half. So total memory could be O(n log n) in worst case if many intermediate strings are kept simultaneously? Let's analyze: In the recursive computation of f(right) (which is of size n/2), it will similarly allocate strings for its halves. The total memory at any time is roughly the sum of sizes of strings currently allocated across the call stack. Since recursion depth is log n, and at each level there might be a string of size proportional to the size of that subtree being constructed? But each active call holds local strings of the size of its input? Actually, the input itself is not copied; we are using slices perhaps. The algorithm we propose will likely take the original string as a reference and pass indices, but return a new string (the canonical form) for that substring. So each call returns a string that is a copy of that substring in canonical order. The memory allocation per call is O(length of substring). The number of simultaneously alive strings: At any point, the recursion is depth-first. Consider the order: f(s) calls f(left) which computes and returns L. That call returns and L is stored in parent variable. Then f(s) calls f(right). During the execution of f(right), the parent frame holds L (size n/2). And inside f(right), we have recursion: f(right) calls f(right.left) etc. At the deepest of f(right) recursion, we have a stack of frames: top (size n) holding L; then its child f(right) (size n/2) holds? It will eventually hold its own L and R after they are computed, but while computing its left, it hasn't gotten its R yet, so at that time it might hold a string from its left child? Actually, careful: In the computation of f(right), it will first call f(right.left). That call will compute and return a string of size n/4. That return is stored in L1 variable in f(right). After that, f(right) calls f(right.right) to get R1. During the call to f(right.right), f(right) holds L1 (size n/4). So we have: top frame holds L (n/2). f(right) frame holds L1 (n/4). f(right.right) recursion goes deeper. So the total memory of live strings from returns is sum: n/2 (L) + n/4 (L1) + n/8 (L2) + ... = n. Plus, at each level, there might be strings being constructed? Actually when a call returns, it constructs a new string and returns it, which is then stored in the parent. So the total memory used at any point is O(n). Because the sum of sizes of all strings that are currently stored in frames along the stack is at most the sum of a geometric series with ratio 1/2, which is less than n. Also, the recursion frames themselves store references or indices, not copies. So the memory is O(n) for the returned strings plus O(log n) stack. That seems acceptable.
However constructing strings of size n repeatedly might cause O(n log n) time due to copying at each level: each character will be copied many times through concatenations. Let's examine: At the leaf (length 1), f returns a string of length 1 (the character). At the next level, two strings of length 1 are concatenated to form a string of length 2. That concatenation copies 2 characters. Then at next level, two strings of length 2 are concatenated to length 4, copying 4 characters, etc. The total copying per level: at level where strings are of size k, there are n/k such nodes, each copying k characters? Actually the recursion tree: each node corresponds to a substring of length len. At each node, we copy its two children strings into a new string of length len. So the total work at each level (all nodes of that size) is sum over nodes: len per node. Since there are n/len nodes at that level, total copy at that level = n. Levels: len = 1,2,4,... n (but note leaves length 1? Actually we treat base case when len is odd and not divisible? But in our recursive algorithm we only split when len is even. However if length is not a power of two, the splits may produce odd lengths eventually. The recurrence may not be perfectly balanced. But still the total copying will be O(n log n) in typical case? Let's analyze worst-case: Suppose n is a power of 2. Then we split all the way down to length 1. There will be log2 n levels (excluding leaves). At each level, total characters copied is n. So total O(n log n). That's acceptable for n=200k (log2(200k) ~ 18). So O(n log n) ~ 3.6 million char copies, very fine.
But what about non-power-of-two? The tree may be unbalanced, but total work still O(n log n) as each character is copied once per level of recursion. Since recursion depth is at most O(log n) but may be O(n) if the splits produce odd lengths? Consider length = prime? Actually if length is odd, we don't split at all; we just return the substring itself (which could be long). But we will not recursively break it further. So if the entire length is odd, we just compare the strings directly. But the problem states that both strings have same length. So if length is odd and they are equal, they are equivalent; otherwise not. So we can quickly check that.
But more generally, if the length is not a power of two, we may have mixed splits. For example, length = 6. Split into 3 and 3. Each half length 3 is odd, so we don't split further; we just return the substring. So recursion depth is only 2 levels. So total copying: for each half of length 3 we return the substring as is (if we implement by returning a copy, we will copy 3 characters each). Then at the top we copy 6 characters to concatenate them. So total copying = 3+3+6 = 12 characters, less than n log n = 6*~2.6=15. So it's fine.
But we need to be careful: When the length is odd, we should just return the substring itself. But if we return a copy, that's O(len) copying. That's okay. However we could avoid copying by returning a string view or just compare without building full representation? But we need to compare canonical forms of two strings. The algorithm: compute canonical representation of a and b, then compare them for equality. Alternatively, we can compute recursively while comparing without constructing full canonical strings, to save time and memory. For equivalence checking, we could implement a function that directly compares two substrings for equivalence, using divide and conquer and memoization (like using hashing to avoid repeated work). But since n up to 200k, O(n log n) is fine.
Let's design algorithm:
Define function canonical(s: string, start, end) returns string; but we can pass a string reference and indices. However constructing substrings by copying may be heavy if we copy large substrings many times. But our recursion copies each character O(log n) times, as argued. So it's okay.
Simplify: Use a recursive function that takes a string as argument (by value? But if we pass by value we copy the whole string each call, which would be O(n^2). So we must pass by reference (const string&) with indices. In C++ we can use string_view or just indices. We'll implement a function that takes the whole string and a start index and length, returns the canonical string.
Pseudo:
string canonical(const string& s, int l, int r) // [l, r) half-open
int len = r - l;
if (len % 2 == 1) {
// base case odd: return substring as is
return s.substr(l, len);
} else {
int mid = l + len/2;
string left = canonical(s, l, mid);
string right = canonical(s, mid, r);
if (left <= right) return left + right;
else return right + left;
}
But this will copy substrings at each step. However the base case odd uses substr which copies. For even length, we call recursively and then concatenate. This is straightforward.
Now, we can compute canonical for both input strings a and b, and then check if they are equal.
But note: The input length up to 200k. In worst-case when length is a power of two, the recursion depth is about 18. The total copies: as earlier, O(n log n) ~ 200k*18=3.6 million char copies, which is fine. However each concatenation constructs a new string, which might allocate memory. The total memory allocations could be many, but still manageable.
But there is a catch: If the string length is large but not a power of two, we still might have some deep recursion? For instance, length could be 200000, which is even, split into 100000 and 100000. Then each half may be even? 100000 is even, split into 50000, etc. So it will split until odd lengths appear. The maximum depth: while length remains even, we keep splitting. The number of times we can split until odd is at most the exponent of 2 in n. The max exponent for numbers up to 200k is about 17 (since 2^17=131072, 2^18=262144 >200k). So depth is at most 18. So recursion depth is safe.
Thus the direct canonical approach is simple and efficient.
Alternative approach: Use recursion with hashing and compare without building strings. For educational purposes, we can also implement a function equivalent(l1,l2,len) that returns true/false. But we need to compare halves efficiently. Could use rolling hash to compare strings quickly. But then we also need to compare crosswise. We could compute hash of halves and check if equal. But we also need to recursively check equivalence, not just equality. So we need to compute hash that captures equivalence class. That is, we could define a canonical hash that combines hashes of halves sorted. This is similar to computing a Merkle tree with sorted children. That would be O(n log n) as well but with less copying. However implementing a stable hash with sorting may be trickier. The string copying method is simpler.
Potential pitfalls: The strings can be long, and recursion depth is low, but recursion may cause stack overflow if we use recursion with depth ~18? That's fine. But if we implement recursion on each half, we may have many recursive calls. However the number of calls is about 2 * (number of nodes) which is about 2n in worst case? Actually in the tree, number of nodes is O(n) because each leaf is a base case (odd length or length 1). For power of two, number of nodes is 2n-1. For n=200k, that's ~400k calls. That's a lot of function calls! Each call does some work, but recursion depth is shallow; however total number of recursive calls could be up to 2n, which is about 400k, which is fine. But each call returns a string, constructing it. However the recursion tree may cause a large number of allocations. But 400k allocations of small strings? Actually each leaf returns a string of length 1 (so allocation of 1 char). Each internal node returns a string of length equal to its subtree. The total amount of character data copied is O(n log n). The number of distinct string objects created is O(number of nodes) which is O(n). That is up to 400k string objects. In C++, constructing and destructing that many strings may have overhead but probably still okay for 200k. However typical time limit might be 1 second? Let's check typical constraints: Codeforces problem 559B (Equivalent Strings). I recall this problem. The typical solution is using recursion with early pruning and comparing substrings using hashing or direct equality. Many solutions use a recursive function that compares two substrings without building whole canonical strings, using lexicographic comparison and recursion. Or they use a function that returns the minimal string after canonicalization. But they often rely on recursion that splits and sorts. The memory/time with strings may be acceptable.
But I'm cautious: In C++, if we implement as described, for each node we allocate a new string via concatenation, which involves memory allocation. For 400k nodes, there may be many allocations, but many are small. The total allocation size is about n log n ~ 3.6 million characters, which is about 3.6 MB. That's fine. However the number of allocations (calls to new) may be high; each concatenation typically allocates a new buffer. But many modern compilers with small string optimization may avoid heap allocation for small strings (e.g., up to 15 characters). For leaves of length 1, they use SSO, so no heap. For internal nodes, the strings become larger, but number of allocations for each node is at most 1 (for the result). So total heap allocations for strings of size > SSO threshold (maybe 15) would be for nodes where length > 15. That's many but not extreme. For n=200k, the number of nodes with len > 15 is about number of nodes at levels where len >= 16. In a binary tree where leaves are odd-length, the count of such nodes is less than 2n/16? Actually let's estimate: For a full binary tree down to size 1, the number of nodes with size >= s is at most 2n/s? Not exactly. For power-of-two sizes, nodes at levels where len >= s: the number of nodes of size exactly len is n/len. So total nodes with len >= s is sum_{len = s,2s,4s,...} n/len = n*(1/s + 1/(2s) + 1/(4s) + ...) = (2n)/s. So for s=16, nodes with len>=16 <= 2*200k/16 = 25k. So about 25k heap allocations. That's fine.
Thus the canonical string method should pass.
But we need to be careful about recursion limit. C++ default recursion limit is usually around 1000, so depth 18 is fine. However number of recursive calls (total invocations) is not limited by depth; the recursion function will call itself many times but not exceed stack depth because it's a tree, but the call stack depth is the depth of recursion (max 18), not total calls. So fine.
However there is a nuance: The canonical string approach returns a string for each substring. For large substrings at higher levels, concatenating left+right may involve copying the entire left and right strings. This is O(len) per node, leading to total O(n log n) characters copied, as argued. That's acceptable.
But could there be a scenario where recursion leads to exponential time? No, because each node's work is linear in its length.
Thus I'll implement that.
But wait: The problem originally from Codeforces is known as "Equivalent Strings". Many solutions use a clever recursion: compare two strings a and b: if they are equal return true; if length odd return false; else return (equivalent(a1,b1) && equivalent(a2,b2)) || (equivalent(a1,b2) && equivalent(a2,b1)). However that naive recursion can be O(n^2) because of repeated comparisons. But we can optimize: If we first compare a1 and b1 for equality quickly (maybe using substring compare or hash), we can avoid recursion in some cases. However the canonical approach is simpler: compute minimal representation for each string and compare.
Alternatively, we can compute the canonical representation using recursion but with memoization? Not needed.
One more nuance: When length is even, we compute canonical of halves. Then we compare the two canonical strings lexicographically to decide concatenation order. That gives a canonical form. This canonical form is essentially the "sorted" representation if we consider the two halves as unordered.
Now I'll implement.
Implementation steps:
- Read two strings s1, s2.
- If s1.length() != s2.length(): but problem says same length, so ignore.
- Compute canonical representation of s1: canonical(s1)
- Compute canonical representation of s2: canonical(s2)
- If canonical(s1) == canonical(s2), print "YES", else "NO".
Edge Cases:
- If length is 0? Minimum is 1.
- If length odd and strings equal: canonical returns the string itself, so compare directly.
- If length odd and strings not equal: canonical forms will be different, so output NO.
Now test with given examples.
But we must ensure canonical(s) returns a string that is exactly the normalized representation. Let's test with odd lengths: s="abc", canonical returns "abc". That's fine. Two strings of length 3: if they are equal then YES else NO. So our algorithm would produce YES only if they are identical, which matches definition (since they are equal; there is no split because length odd, so equivalence only if equal). Good.
Now test with length 2: s="ab", canonical: left="a", right="b", left<right => return "ab". For "ba": left="b", right="a", left>right => return "ab". So both become "ab". Then comparison yields YES. Good.
Now test with length 4: s="aabb": left="aa", right="bb". For "aa": left="a",right="a" => left<=right => "aa". For "bb": "bb". Compare left="aa", right="bb": "aa"<="bb" => return "aabb". For "abab": left="ab", right="ab". For "ab": becomes "ab". So both halves "ab","ab": left<=right => "abab". So different.
Now test a more complex: s1 = "aaaabbbb", s2 = "aaaabbbb"? They are already sorted? Actually canonical of "aaaabbbb" will be? Split "aaaa","bbbb": each half canonical: "aaaa" and "bbbb". Compare -> "aaaabbbb". So identical.
Now test s1="abba", s2="baab". s1: split "ab","ba": left "ab" -> canonical "ab", right "ba" -> canonical "ab". Compare left="ab", right="ab": equal => return "ab"+"ab"="abab". s2: "baab": split "ba","ab": left "ba"-> canonical "ab", right "ab"-> canonical "ab". Compare equal => return "ab"+"ab"="abab". So YES. Let's verify if they are indeed equivalent according to definition: "abba" and "baab"? Check: Split "abba" into "ab","ba". "baab" into "ba","ab". Compare a1="ab" with b2="ab" -> equivalent? Yes (they are equal). a2="ba" with b1="ba" -> equal. So indeed equivalent. Good.
Now test s1="abcd", s2="acbd"? Not sure. Anyway.
Thus algorithm works.
Now implementation details:
We'll write a helper function:
string normalize(const string& s, int l, int r) {
int len = r - l;
if (len % 2 == 1) {
return s.substr(l, len);
} else {
int m = (l + r) / 2;
string left = normalize(s, l, m);
string right = normalize(s, m, r);
if (left < right) return left + right;
else return right + left; // if equal, order doesn't matter; we can do left+right.
}
}
But careful: For large strings, using substr returns a new string copying the substring. That's okay because base case odd length could be large if the length is odd and not 1. For example, if total length is 200000 and it's odd, then we will directly compare the whole strings. In that case, the recursion will be: normalize called on the whole string, length odd, so it returns s.substr(0,n). That's a copy of the whole string. Then we compare the two copies? Actually we will compute normalize for both strings, each returns a copy of the original if odd. Then we compare them. That's O(n) time and O(n) memory, which is fine.
But for even lengths, we will recursively build strings.
Potential optimization: If left and right are equal, concatenation order doesn't matter, but we choose left+right (or right+left). So it's fine.
Now complexity: In worst case (power of two length), each character will be copied log2 n times. That's acceptable.
But we must consider that strings can be up to 200k, and recursion depth is low. However total number of function calls may be high (around 2n). Each call involves some overhead (function call, string allocations). But 400k calls is fine in C++ with optimizations.
However there is a potential stack overflow if we use recursion without caution? Recursion depth is low, but each call creates a stack frame. The number of simultaneous frames is depth, not total calls. So safe.
Memory usage: At any time, we may have up to O(n) characters in strings alive across the stack. As argued, that's about n plus something. For n=200k, that's fine.
But we need to be careful with memory fragmentation? Not an issue.
Thus I'll implement this.
But is there any more efficient method? Possibly we can avoid copying large strings at the top level by comparing canonical forms directly without building both fully. For instance, we can compute canonical of both and compare incrementally? But not needed.
Potential pitfalls: The recursion may produce a lot of temporary strings that get destroyed, but that's fine.
However, we should be aware of the worst-case where length is 200000 and is a power of two? 200000 is not a power of two; the nearest power of two is 131072 or 262144. So depth is at most 17. Total copies: For n=200k, the number of times each character gets copied might be up to the number of levels it appears in, i.e., the number of times the substring containing that character is even length and split. In a full binary tree (power of two) each character appears in all nodes on the path from leaf to root, i.e., log2 n times. For n=200k, log2(200k) ~ 18. So about 3.6 million char copies. That's trivial.
Thus we can implement.
But there is a catch: The recursion may be called many times for small substrings. For instance, if the string length is 200000 and is even, we split into 100000 and 100000. Each half may be even, etc. The total number of nodes: For full binary tree of size n (power of two), nodes = 2n-1 ~ 400k. For non-power-of-two, nodes may be fewer. So about 400k nodes. Each node we do a string concatenation. In C++, string concatenation operator+ (for two strings) creates a new string that is the concatenation. This involves allocation of a new buffer and copying of both strings. That's fine.
But maybe we could improve by using string views or by returning a tuple of references? Not needed.
Thus solution.
Now we can code.
Implementation in C++:
#include
#include
using namespace std;
string normalize(const string& s, int l, int r) {
int len = r - l;
if (len % 2 == 1) {
return s.substr(l, len);
} else {
int m = (l + r) / 2;
string left = normalize(s, l, m);
string right = normalize(s, m, r);
if (left < right) {
return left + right;
} else {
return right + left;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string a, b;
getline(cin, a);
getline(cin, b);
// remove possible trailing newline? getline will read line without newline.
// but input may have spaces? No, only lowercase letters, so getline fine.
// Alternatively use cin >> a >> b; but strings may have no spaces.
// Since strings are on separate lines, both methods work.
// But they can be up to 200k, so using cin >> is fine.
// Let's use cin >> a >> b for simplicity.
// But if strings contain whitespace? They don't.
cin >> a >> b;
string na = normalize(a, 0, a.size());
string nb = normalize(b, 0, b.size());
if (na == nb) {
cout << "YES\n";
} else {
cout << "NO\n";
}
return 0;
}
But we need to ensure that we don't exceed recursion depth? Depth is ~18, fine.
Potential optimization: If the two strings are already equal, we can return YES early. But not necessary.
However there's a subtlety: The definition says: They are equivalent if either they are equal, or if after splitting, one of the two conditions holds. The canonical representation algorithm essentially sorts halves, which leads to a unique representation for each equivalence class. But is it valid for all strings? Let's reason: For any string s, define f(s) as described. Claim: For any two strings a,b of same length, they are equivalent according to the problem iff f(a) == f(b). We'll prove briefly: f(s) is in the equivalence class of s (i.e., f(s) is equivalent to s). This can be shown by induction: If length odd, f(s)=s, so equivalent. If even, f(s) is either left+right or right+left. Since by induction left ~ f(left) and right ~ f(right), and because the two halves can be swapped if they are equivalent? Actually we need to show that f(s) is equivalent to s. For even length, s = s1 + s2. f(s1) ~ s1, f(s2) ~ s2. f(s) is either f(s1)+f(s2) or f(s2)+f(s1). If the latter, then we need to show that s1+s2 is equivalent to f(s2)+f(s1). Since s1 ~ f(s1) and s2 ~ f(s2), we can recursively show that swapping is allowed? The definition says that two strings a,b are equivalent if after splitting, either (a1b1 and a2b2) OR (a1b2 and a2b1). So if we let a = s1+s2, b = f(s2)+f(s1). We need to show they are equivalent. Since s1f(s1) and s2f(s2), we can attempt to match a1=s1 with b1=f(s2)? Not directly. But we can prove by constructing a series of swaps using the equivalence relation. Actually more straightforward: We can define f(s) as the lexicographically smallest string in the equivalence class of s (or a canonical representative). It's known that this sorting approach yields the minimal string in the class under lexicographic order. But we need to be sure the equivalence relation is exactly the one generated by allowing swaps of halves when halves are equivalent. It is indeed a well-known problem; the solution is to recursively sort the halves. Many accepted solutions use exactly this method.
I recall that there is a known Codeforces problem 559B "Equivalent Strings" and many solutions use this approach: string smallest(string s) { if (s.length() % 2) return s; string s1 = smallest(s.substr(0, n/2)); string s2 = smallest(s.substr(n/2)); return min(s1+s2, s2+s1); } Then compare smallest(a) == smallest(b). That is exactly what we plan.
Thus it's correct.
Edge Cases: Very large strings: recursion depth fine.
Now we should consider performance: For n=200k, the total number of nodes may be up to about 400k. Each node does a concatenation of two strings, which is O(len) copy. For nodes of large len, they copy many characters. But total copies as argued O(n log n). For n=200k and log2~18, that's 3.6 million copies, which is trivial. However the actual number of characters copied might be more due to overlapping recursion? Let's compute more precisely: In a full binary tree with n leaves, each internal node of size k copies k characters. Sum_{k=1,2,4,...,n} (number of nodes of size k) * k. Number of nodes of size k = n/k. So sum = n/k * k = n for each level? Wait: For each level where size = k, there are n/k nodes. Each node copies k characters, so total per level = n. Number of levels = log2 n. So total = n log2 n. So indeed 200k * 18 = 3.6M. That's fine.
But there is also copying for leaves? Leaves are base case odd lengths. In full binary tree, leaves are length 1, which are odd, so they return substr(0,1). That copies 1 character per leaf, and there are n leaves. So that adds n copies. But that is included in the total? Actually the leaf copies are separate: they return a string of length 1, which copies from original string. So leaf copies add n more. So total copies maybe ~4.6M. Still fine.
But note: For leaves of odd length >1 (when length is not power of two), we may have leaves with length >1, which copy that many characters. But the sum over all leaves of their lengths is n. So leaf copies total n as well. So overall total characters copied maybe around n log n + n = O(n log n).
Thus runtime is fine.
Potential memory: At the top level, we create two normalized strings na and nb, each of length n. So 400k characters. Plus temporary allocations during recursion, but they get freed. So memory usage about O(n) plus recursion overhead.
Now ensure we use fast I/O and avoid unnecessary overhead.
Thus solution is ready.
But wait: There's a nuance: The canonical representation we defined might be not unique? Let's test with an example: s = "abab". f("abab") =? n=4 even: left="ab", right="ab". f("ab") =? length 2: left="a", right="b" => f("ab") = "ab" because left<right. So both halves "ab". Compare left<right? They are equal, so we return left+right = "abab". So f("abab") = "abab". For s = "aabb"? f = "aabb". So they differ.
Now consider s = "baab". f("baab"): left="ba", right="ab". f("ba") => "ab". f("ab") => "ab". So left="ab", right="ab". Equal => return "abab". So f("baab") = "abab". So we have equivalence classes: {"abab", "baab", ...? Also "abba"? Let's compute "abba": left="ab", right="ba". f("ab")="ab", f("ba")="ab". left=right => "ab"+"ab"="abab". So "abba" also maps to "abab". So all these become "abab". But is "abba" equivalent to "abab"? According to definition? Let's test: a="abba", b="abab". Split a: a1="ab", a2="ba". b: b1="ab", b2="ab". Check: a1b1? "ab" ~ "ab" true. a2b2? "ba" ~ "ab"? "ba" and "ab": split each: "b","a" and "a","b". Check: "b""a"? no (since odd length and not equal). So not that. Check cross: a1b2? "ab""ab" true. a2b1? "ba""ab"? "ba" and "ab": as above not equivalent. So neither condition holds. So "abba" is not equivalent to "abab"? Wait, but we earlier thought "abba" and "baab" were equivalent? Let's verify "abba" vs "baab". a="abba", b="baab": split a: "ab","ba"; b: "ba","ab". Check: a1b1? "ab""ba"? Not equivalent. Check cross: a1b2? "ab""ab" true; a2b1? "ba"~"ba" true. So cross condition holds, so "abba" ~ "baab". Good. But "abba" ~ "abab"? We just tested and it seems not. So f("abba") = "abab"? That would suggest they are equivalent. But we found they are not. So something is wrong.
Wait, we computed f("abba"): length 4 even. Left substring: indices 0-2: "ab"? Actually "abba": first half "ab", second half "ba". left = normalize("ab") => returns "ab" (since "ab" length 2, left "a", right "b", "a"<"b" => "ab"). right = normalize("ba") => returns "ab" (since "ba": left "b", right "a", "a"<"b"? Wait in our normalize for "ba": length 2 even, left="b" (char), right="a" (char). left = "b", right = "a". In our code, we compare left < right? "b" < "a"? false. So we return right+left = "a"+"b" = "ab". So right becomes "ab". So left = "ab", right = "ab". Then compare left <= right? left == right, so we return left+right = "ab"+"ab" = "abab". So f("abba") = "abab". But we argued "abba" is not equivalent to "abab". Let's double-check equivalence of "abba" and "abab". Use definition: Two strings equivalent if either equal or can split into halves. Length 4 even. For "abba" and "abab":
a1="ab", a2="ba"; b1="ab", b2="ab".
Option 1: a1b1 and a2b2. a1b1? "ab" and "ab": they are equal => equivalent. a2b2? "ba" and "ab": we need to check if "ba" ~ "ab". For "ba" and "ab": length 2 even. Split: ba: b1'="b", b2'="a". ab: a1'="a", a2'="b". Check: either (b1'a1' and b2'a2') => "b""a"? no; or cross: b1'a2' => "b""b"? yes; b2'a1' => "a""a"? yes. So cross condition holds: "b""b" and "a""a". So "ba" ~ "ab"! Wait, we missed that earlier. Let's recalc: For "ba" and "ab", we split each into single characters. They are not equal, but we can split because length is even (2). After splitting, we have halves of length 1 each. Since they are of length 1, they are compared directly: they are equal only if characters equal. So to check "ba" ~ "ab", we have:
Case: a = "ba", b = "ab". Split: a1="b", a2="a"; b1="a", b2="b".
Check condition 1: a1b1? "b" ~ "a"? Since length 1, they are equivalent only if equal. They are not equal => false.
Condition 2: a1b2? "b" ~ "b"? => true (since equal). a2b1? "a" ~ "a"? => true. So both hold, so "ba" ~ "ab" is true. So indeed "ba" and "ab" are equivalent. Therefore a2b2? "ba" ~ "ab" is true. So option 1: a1b1 (true) and a2b2 (true) => both true. So "abba" ~ "abab" is true! Because both halves are equivalent. So they are equivalent. Wait, but earlier we thought only cross condition could hold, but actually both halves being equivalent also works. So they are equivalent! Let's verify with definition: a1b1 and a2~b2. Since a1="ab", b1="ab" => equivalent. a2="ba", b2="ab" => as we just determined, "ba" ~ "ab". So both conditions satisfied, so yes they are equivalent. So "abba" is equivalent to "abab". Good. So f mapping "abba" to "abab" is consistent; they are in same equivalence class. So earlier miscalculation.
Thus canonical approach seems consistent.
Now consider "aabb" vs "abab". We determined they are not equivalent. f("aabb")="aabb", f("abab")="abab", not equal, so not equivalent. Good.
Now consider "abac" vs "aabc"? Not needed.
So algorithm is correct.
Potential pitfalls: The recursion might cause large recursion depth if the string length is not a power of two? Actually depth is limited by number of times we can split until we hit odd length. The worst case for depth is when the length is a power of two, because we keep splitting until length 1. So depth is log2(n) up to 18. So safe.
Now we should think about using iterative approach? Not needed.
Now we must be careful about time limit if we use C++ and do many string operations. But it's fine.
One more nuance: The problem states that the length can be up to 200,000. In some languages like Python, O(n log n) might be borderline but in C++ it's fine.
Now we need to implement in C++.
Implementation details:
- Use std::string.
- Normalize function as described.
But we can also incorporate early exit: if the two strings are equal, we can output YES immediately. However, the normalization will also catch that.
Potential optimization: If the two strings are already equal, we can skip normalization? But not needed.
Now test with sample:
Input:
aaba
abaa
Our algorithm:
normalize("aaba"): length 4 even -> split "aa","ba".
normalize("aa"): length2 -> split "a","a" -> left="a",right="a" -> return "aa".
normalize("ba"): length2 -> split "b","a" -> left="b",right="a" -> left<right? false -> return "ab". So left="aa", right="ab". Compare left<right? "aa"<"ab" true -> return "aa"+"ab" = "aaab".
normalize("abaa"): split "ab","aa".
normalize("ab"): -> "ab".
normalize("aa"): -> "aa". left="ab", right="aa". Compare "ab"<"aa"? false -> return "aa"+"ab" = "aaab". So both normalized to "aaab". Output YES.
Second sample: aabb -> "aabb", abab -> "abab", not equal, output NO.
Thus matches.
Now, we need to consider that the strings can be large and recursion may cause a stack overflow if we use too deep recursion? log2(200k) ~ 18, safe. So it's fine.
However, one more thing: The function normalize returns a new string. In the base case for odd length, we return s.substr(l, len). This copies that substring. For large odd substrings, that could be large (e.g., if total length is odd, we will copy the entire string). That's fine.
But we could also avoid copying in base case by just returning the original string if it's odd and equal? But we need to compare with the other normalized string. So we need to create a canonical representation for each string individually. So we must copy.
Alternatively, we could compute the canonical representation for both strings simultaneously? Possibly we could compare without constructing both full strings. For example, we could define a recursive function isEquivalent(a, b) that returns bool, using hashing to compare substrings quickly. But the string approach is simpler.
But there is a nuance: In the canonical approach, we sort the halves lexicographically. This is correct because we are constructing a canonical form that is the minimal string under the ordering of the equivalence class. To guarantee uniqueness, we need to define a total order on canonical strings and always place the smaller half first when they are not equal. If halves are equal, order doesn't matter.
Now let's verify that this canonical form indeed yields a unique representative for each equivalence class. This is a known technique.
Thus solution is correct.
Now, double-check if any subtle cases where length is odd but not 1. Example: length 3 strings "abc" and "acb". They are not equal, so should be NO. Our algorithm: normalize("abc") returns "abc"; normalize("acb") returns "acb"; they are different => NO. Good.
Now consider length 0? Not possible.
Now we will code.
But before finalizing, we might consider potential performance improvement: Use string_view to avoid copying in the base case? But base case still needs to produce a string that will be concatenated later. If we return a string_view, it would refer to the original string, but later concatenation would need to copy the data anyway. So it's not beneficial.
Alternatively, we could implement a function that returns the canonical string by passing a reference to a result string and building it in-place? But simpler is fine.
Now we should test on some random cases to ensure correctness. However we trust the known solution.
One more nuance: The problem's equivalence definition says: They are equivalent if either they are equal OR if we split into halves (must be equal length) then either both halves equivalent in order or crosswise. This is exactly the definition for the "smallest" representation.
Now implement.
Potential memory/stack issue: Each recursive call returns a string by value, which may involve moving in C++11 and later, but even if not, it's fine.
Edge Cases: Large strings with many identical characters? e.g., both strings all 'a's. Then normalized strings will be the same. The recursion will produce many identical halves. However, comparisons will be cheap because string comparison is O(len) in worst-case. For example, for a string of all 'a's, at each node we compare two strings of length len/2 that are all 'a's. The comparison will scan the entire strings until it finds a difference, but they are equal, so it will scan entire length. So the total work for comparisons might become O(n log n) as well. Let's analyze: At each node, we compare left and right strings (each of length k). If they are equal, we compare all k characters. So for a uniform string, at each node we do O(k) comparison. Total across all nodes = sum over nodes of O(k) = O(n log n) as before. So still fine.
Now we might consider an optimization: if left == right, we can skip copying? But we already do left+right or right+left; but if they are equal, the order doesn't matter. So we still need to return the concatenated string, which is just left+right (which copies both). That's necessary for building the canonical representation. So total copy per node is O(k). So overall O(n log n) remains.
Now is O(n log n) acceptable for n=200k? n log2 n ~ 200k*18 = 3.6M char copies plus comparisons. That's trivial; even 10 times that would be fine. So no problem.
But wait: In our analysis we assumed that at each node we copy the entire substring (length k) when we return left+right. However, left and right are strings that themselves were allocated. When we do left+right, we allocate a new string and copy both. That means each character gets copied at each level of the tree. So total characters copied is indeed O(n log n). However, we also copy characters for leaf base cases: each leaf returns a copy of its substring. For leaves of length >1 (odd), the copy may be large. But those are relatively few.
Thus total copies maybe a few million. In C++, copying a few million characters is extremely fast (<0.01 sec). So the solution will be very fast.
But there is a catch: The recursion might create a lot of temporary strings that are deallocated, but that's okay.
Now I'll implement in C++.
But I recall that in Codeforces problem 559B, the typical solution often uses a recursive function that compares two substrings without building the whole normalized string, and uses pruning like checking if the substrings are equal via hashing or direct comparison, and then recursively checking the two possibilities. Many solutions used something like:
bool equivalent(const string& s, int a1, int a2, int b1, int b2) {
if (equal) return true;
if (len odd) return false;
// check if substrings are equal via hashing? Or just compare
// Then split and check recursively.
}
But they often needed to avoid O(n^2). They used something like: if two substrings are equal, they are equivalent (since they are equal). So they could check equality quickly using hashing or direct string comparison (which is O(n) per call but could lead to O(n^2) if not careful). However many solutions used "minimal string" approach as we do, which is simpler and passes.
One potential improvement: To avoid many string copies, we could implement a function that returns a string view? But it's fine.
Now, final code.
But wait: I must consider the maximum recursion depth. For n = 200000, the depth is at most 18, safe. However, the number of recursive calls may be large but not cause stack overflow because each call returns before deeper calls? Actually recursion depth is the depth of the call stack. The function is recursive: it calls itself for left, then for right. The depth is the length of the longest chain of recursive calls. That is log2(n) for even splits. So depth is small. However, there could be a scenario where the string length is odd and large, we don't split, so depth 1. So worst-case depth is when string length is a power of two, which yields depth log2(n)+1. For n=200k, that's about 18. So safe.
Now implement.
Potential problem: If we use recursion and the string length is up to 200000, but the recursion will go down to base cases of length 1. That's okay.
Now consider memory: The function returns a string, which may be moved in C++11, but even if not, copying occurs. But as we argued, it's fine.
Now test with a case where strings are extremely long (200k) and all 'a's. Then normalized string for both is "a"*200k. However, our recursive process: At each split, left and right are identical strings of 'a's. So the comparison left < right will compare the two strings, which are equal, so it goes through all characters each time. So at each node of size k, we do a comparison of two strings of length k/2? Actually left and right are of length k/2? Wait: For a node handling a substring of length len, left and right are the canonical forms of the halves, each of length len/2. So comparison of left and right is O(len/2) = O(len). So total time for comparisons also O(n log n). For n=200k, that's also few million char comparisons, which is fine.
But note: The comparison for equality (when strings are equal) will traverse the entire strings. That's okay.
Now, I'll code.
However, we must be careful: The input strings may contain newline characters? We'll read using cin >>.
Now, I'll produce final answer.
But there is a nuance: The canonical form we produce is a string. For two large strings, we allocate two copies of the entire string (the normalized forms). This uses 2*n memory. That's fine. Additionally, temporary strings allocate extra memory but are freed.
Now, let's think about the possibility of stack overflow due to many recursive calls? The number of simultaneous frames is depth, but the total number of function calls is high, but they are not all on the stack at once because recursion is depth-first. The call stack at any time contains at most O(log n) frames. So no overflow.
Thus solution is good.
But wait, maybe we should consider an iterative approach using a stack to avoid recursion? Not needed.
Now I'll produce the final answer.
But before finalizing, I'd like to double-check the correctness on some tricky cases.
Case: strings of length 1: "a" and "a" -> YES. Our algorithm: normalize both returns "a" and "a", equal.
Case: length 1: "a" and "b" -> NO.
Case: length 2: "aa" and "aa" -> YES. normalize("aa"): left="a",right="a", return "aa". So both "aa". YES.
Case: length 2: "ab" and "ba" -> YES as shown.
Case: length 4: "abcd" and "cdab". Are they equivalent? Let's compute f("abcd"): split "ab","cd". f("ab")="ab", f("cd")="cd". Compare "ab"<"cd"? yes -> "abcd". f("cdab"): split "cd","ab". f("cd")="cd", f("ab")="ab". Compare "ab"<"cd"? Since left="cd", right="ab", left<right? "cd"<"ab"? false -> return "ab"+"cd" = "abcd". So both become "abcd", so YES. Indeed check: a="abcd", b="cdab": split a1="ab",a2="cd"; b1="cd",b2="ab". Check cross: a1b2? "ab""ab" true; a2b1? "cd""cd" true -> equivalent. So YES.
Case: length 4: "acbd" and "abcd"? Let's test: "acbd": split "ac","bd". f("ac")="ac", f("bd")="bd". Compare "ac"<"bd"? yes -> "acbd". "abcd": split "ab","cd". f("ab")="ab", f("cd")="cd". Compare "ab"<"cd"? yes -> "abcd". Different, so NO. Indeed they are probably not equivalent.
Now, consider length 8: "aabbaabb" and "abaaabab"? Hard to tell but our algorithm should work.
Now, there is a known solution that uses recursion with string views and early pruning, but our approach is standard.
Thus final solution.
Potential pitfalls: The input strings might have leading/trailing whitespace? We'll just use cin >> string, which reads a word (sequence of non-whitespace). The strings consist of lowercase English letters, so fine.
Now produce final answer.
But we should consider that the recursion may be too slow if we use many string copies due to memory allocation overhead. However it's fine.
We could also implement a function that returns a string by moving to avoid extra copies, but the compiler's return value optimization (RVO) may handle it. For example, when returning left+right, it constructs a temporary and then returns it; RVO may avoid extra copy.
We can also implement using std::string concatenation with reserve to avoid reallocation? Not necessary.
Now code.
But wait: There's a subtlety: For even length, we need to split into two halves of the same size. That is floor(len/2) but since len is even, it's exact. In our code we use (l+r)/2 integer division, which works for even lengths. But for odd length we don't split.
Now edge case: When length is 0? Not possible.
Now I'll write the final solution.
However, I recall that some solutions to this problem used a different approach: compare recursively, but with optimization: if the two substrings are equal, return true; if length odd, return false; else split and check. And to avoid repeated work, they would first compare the first halves quickly using a hash? But our approach is fine.
But there is a nuance: In our canonical approach, we are building a normalized string for each input. For very long strings (200k) that are not powers of two, the recursion may not be perfectly balanced, but it's still O(n log n). For example, if length = 199999 (odd), we only copy the string once (base case) and compare. So it's O(n). Good.
Now I'll implement.
After implementing, test with the sample:
Input:
aaba
abaa
Expected YES.
Our code should output YES.
I'll test mentally.
Now I will write the final answer.
But before final, consider potential bug: In the base case, when length is odd, we return s.substr(l, len). However, if the string length is odd but greater than 1, we treat it as leaf. But is that correct according to definition? Suppose length is odd but >1. The definition: Two strings are equivalent if they are equal. There is no splitting because you can't split into two halves of equal size (since length odd). So yes, equivalence only if they are equal. So canonical representation should be the string itself, because there is no transformation possible. So returning the substring itself is correct.
Now, what about length even but we could also have odd length after splitting? That's handled recursively.
Thus solution is correct.
Now we should produce final output with "YES" or "NO".
Implementation:
#include <bits/stdc++.h>
using namespace std;
string normalize(const string &s, int l, int r) {
int len = r - l;
if (len & 1) {
return s.substr(l, len);
} else {
int m = (l + r) / 2;
string a = normalize(s, l, m);
string b = normalize(s, m, r);
return (a < b) ? (a + b) : (b + a);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string a, b;
cin >> a >> b;
string na = normalize(a, 0, a.size());
string nb = normalize(b, 0, b.size());
cout << (na == nb ? "YES" : "NO") << endl;
return 0;
}
But note: This will read the strings separated by whitespace. Input is on separate lines, but cin >> reads tokens separated by whitespace, so it's fine.
Now test with a simple case: a = "a", b = "b". na = "a", nb = "b", not equal => NO.
Now consider a = "ab", b = "ba". na: left="a",right="b", a<b => "ab". nb: left="b",right="a", b<a? Actually left="b",right="a", compare left<right? "b"<"a" false, so return "a"+"b"="ab". So both "ab" => YES.
Now consider a = "aa", b = "ab". na: "aa", nb: "ab" -> NO.
All good.
Now confirm that the code works for large input.
Now I'll produce final answer.
But there is one more nuance: The function normalize returns a string. For each recursive call, we are returning a new string. This could lead to many allocations and deallocations. However, given constraints, it's fine.
But we might want to add an optimization: If the two strings are equal, we can output YES immediately without normalization. That could save time for cases where strings are equal but large odd length. But not necessary.
Now, final answer.
I'll produce the code accordingly.
Note: Some compilers may have issues with recursion depth? No.
Now output.
Now double-check the memory usage: In the worst case (power-of-two length), the recursion will generate many strings. However, we can improve by using references and building the normalized string in place using a global buffer? But not needed.
Thus final solution.
Let's also consider if there is any possibility of overflow in recursion due to many calls: 400k function calls is fine; function call overhead might be a bit high but still within limits.
Now produce final answer.
But I recall that Codeforces problem 559B has time limit 2 seconds. Our O(n log n) with string copying should pass easily.