Apple OA question - SDET IST - 6 you

361
Sep 12, 2026

/**

  • Write a program to "factorize" the extremities of two ASCII strings {@code str1} and {@code str2}.
  • Your must return a single string, initially made from the concatenation of two given strings.
  • The longest substrings that is common between the end of the first string and the beginning
  • of the second one must be factorized (written only once).
  • You must decide the concatenation order {@code str1 + str2} or {@code str2 + str1} so that
  • you get the best factorization.
  • When the same number characters can be factorized by the two concatenation
  • orders, prioritize {@code str1 + str2}.
  • Detailed example

  • With these parameters:
    • <li>{@code str1 = "1234yyabc"}</li>
    • <li>{@code str2 = "abcxxxx1234"}</li>
  • If you choose the order {@code str1 + str2} you could factorize the substring {@code "abc"}. Then,
  • you would return {@code "abcxxxx1234yyabc"}.

*/

public class Factorize {

public static int redundant(String first, String second) {
    for (int idx = second.length() - 1; idx >= 0; idx--) {
        String sub = second.substring(0, idx);
        if (first.endsWith(sub)) {
            return sub.length();
        }
    }

    return 0;
}

/**
 * @param str1 The first ASCII string to factorize.
 * @param str2 The second ASCII string to factorize.
 * @return The result string, after concatenation and factorization.
 */
public static String factorizeExtremities(String str1, String str2) {
    if (str1.equals(str2)) {
        return str1;
    }

    int firstOcc = redundant(str1, str2);
    int secondOcc = redundant(str2, str1);
    if (secondOcc > firstOcc) {
        return str2.concat(str1.substring(secondOcc));
    }
    return str1.concat(str2.substring(firstOcc));
}

public static void main(String[] args) {
    System.out.println("Using example: " + factorizeExtremities("1234yyabc", "abcxxxx1234"));
    System.out.println("Using example: " + factorizeExtremities("UUUUUUUUUUUUUU", "UUUUU"));
}

}

Comments (1)