Extract with String.substring()
Write a Java function that takes a string and two indices, and returns the substring from beginIndex (inclusive) to endIndex (exclusive) using String.substring().
String.substring() is a method that returns a new string that is a substring of the original string. The beginIndex is inclusive, and the endIndex is exclusive. If endIndex is omitted, the substring extends to the end of the string. Indices are zero-based.
In Java 7+, substring() creates a new character array instead of sharing the original's backing array (as Java 6 did). This prevents memory leaks from holding large strings but creates a new copy for each call. The method throws IndexOutOfBoundsException if the indices are invalid.
Time complexity is O(n) where n is the substring length (due to the char[] copy). Space complexity is O(n) for the new substring. The method validates that beginIndex >= 0, endIndex <= length, and beginIndex <= endIndex.
Edge cases include extracting the entire string (0, length), extracting an empty string (beginIndex == endIndex), extracting from the beginning (0, n), and extracting to the end (n, length).
Example Input & Output
Empty substring
Characters 1 to 4
First character
Full string
Last two chars
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String s, int start, int end) {
return s.substring(start, end);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
