Determine if a String has a mirroring head and tail Problem statement:


  Given a string, look for a mirror image (backwards) string at both the
  beginning and end of the given string. In other words, zero or more
  characters at the very begining of the given string, and at the very
  end of the string in reverse order (possibly overlapping). For
  example, the string "abXYZba" has the mirror end "ab".


Examples:


mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"


Below is my solution to the problem in java: 

public String mirrorEnds(String string) {
    final int len = string.length();
    final int half = len / 2;
    String result = "";

    for (int i = 0; i &lt; half; i++) {
        if (string.charAt(i) != string.charAt(len -1 -i)) {
            break;      
        } else {
            result += string.substring(i, i + 1);
        }
    }
    return result.length() == half ? string : result;
}


Is it safe to say that in terms of time complexity the solution is optimal already? Any other review comments are also welcome.
Below your question:


  Is it safe to say that in terms of time complexity the solution is
  optimal already?


Yes, you are comparing chars from front and back of the string and stop when you encounter two different chars so this is a complexity O(n).

Some minor changes to your code, instead of iterate over your string transform it to a char array and instead of break the cycle return directly the result with the use of a StringBuilder for the result:

char[] arr = string.toCharArray();

StringBuilder builder = new StringBuilder();
for (int i = 0; i &lt; half; ++i) {
    if (arr[i] != arr[len -1 -i]) {
        return builder.toString();
    }
    builder.append(arr[i]);
}

return string;


In this way you avoid the use of consecutive creation of substrings and the code is simpler.

Your method can be rewritten then in this equivalent way:

public static String mirrorEnds(String string) {
    final int len = string.length();
    final int half = len / 2;
    char[] arr = string.toCharArray();

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i &lt; half; ++i) {
        if (arr[i] != arr[len -1 -i]) {
            return builder.toString();
        }
        builder.append(arr[i]);
    }

    return string;
}