GetMiddle

You are going to be given a non-empty string. Your job is to return the middle character(s) of the string. If the string’s length is odd, return the middle character. If the string’s length is even, return the middle 2 characters.

Two main key-concepts

  1. length is odd get middle number of string
  2. length is even get middle 2 character
public static String getMiddle(String word) {  
    //Code goes here!  
    int length = word.length();  
    if(length == 0) return null;  
    return length%2 != 0 ? String.valueOf(word.charAt(length/2)) : word.substring(length/2-1,length/2+1);  
}

Most part is return substring 2 characters. This method has complexity O(n)

We can improve to O(1), BY replacing substring to charAt

public static String getMiddle(String word) {  
    //Code goes here!  
    int length = word.length();  
    if(length == 0) return null;  
    return length%2 != 0 ? String.valueOf(word.charAt(length/2)) : word.charAt(length/2-1) + "" + word.charAt(length/2);  
}
Last modified April 7, 2025: update codewar (7e82e67)