public static String getMiddleString(String S, String T)
{
if(S.length()<T.length()){
for(int i=0;i<(T.length()-S.length());i++)S = '`'+S;
}
if(T.length()<S.length()){
for(int i=0;i<(S.length()-T.length());i++)T = '`'+T;
}
int N = S.length();
// Stores the base 26 digits after addition
int[] a1 = new int[N + 1];
for (int i = 0; i < N; i++) {
a1[i + 1] = (int)S.charAt(i) - 97
+ (int)T.charAt(i) - 97;
}
// Iterate from right to left
// and add carry to next position
for (int i = N; i >= 1; i--) {
a1[i - 1] += (int)a1[i] / 26;
a1[i] %= 26;
}
// Reduce the number to find the middle
// string by dividing each position by 2
for (int i = 0; i <= N; i++) {
// If current value is odd,
// carry 26 to the next index value
if ((a1[i] & 1) != 0) {
if (i + 1 <= N) {
a1[i + 1] += 26;
}
}
a1[i] = (int)a1[i] / 2;
}
String result ="";
for (int i = 1; i <= N; i++) {
result+=(char)(a1[i] + 97);
}
return result;
}
This is code that I took from https://www.geeksforgeeks.org/find-the-string-present-at-the-middle-of-a-lexicographically-increasing-sequence-of-strings-from-s-to-t/ to help me find the string in the middle between 2 strings in lexicographical order (e.g. the middle string between "z" and "ad" is "ab". The idea is that it treats the strings as base-26 numbers and gets the number in the middle of them and changes it back to a string.The code from the blog only works with same length strings, so I modified it and it seems to work but I'm not exactly sure why and I'm also not sure if it would work with all cases, I would appreciate it if someone would explain why my modification is correct or incorrect.
The modification was the 2 if conditions on top, it basically prefixes the smaller string with "`" characters (ASCII=96). Initially I tried prefixing with "a", but that didn't work, so I thought of trying the character just before "a" in ASCII.
In my case when I talk about lexicographical ordering I mean: a,b,c.....y,z,aa,ab,ac,ad...zz,aaa,aab.....