saryal saryal - 1 year ago 58
Java Question

Does the code take constant space in memory for any given input?

public static String switchString(String word, int i, int j) {
StringBuilder newString = new StringBuilder();
newString.append(word.substring(j, word.length()));
newString.append(word.substring(i + 1, j));
newString.append(word.substring(0, i + 1));
return newString.toString();

For a given input string and index i and j, the code should do something like this:
if word = “abcdef” and i=1, j=3.
Output should be: “defcab”

Assuming that the word is not null and i and j are not index that are out of bound, the code works fine. I wanted to know if for a string of any given length, does it take a constant space is memory via this approach.

Answer Source

In Java, Strings are immutable. Calling substring makes a new String.

If your String word is some length n, you end up generating substrings with a total length of n.

Whatever the size of StringBuilder is is constant. Whatever metadata is stored in each String is also constant. What changes is the length of the string.

Thus, no, this approach does not use constant space, but n space.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download