0
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 indexes 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 out of bounds, the code works fine. I want to know if, for a string of any given length, does this program take constant space in memory via this approach.

3
  • Not sure what you expect it to do but i think you get a OutOfRange exception or someting like this at newString.append(word.substring(j, word.length())); Commented Oct 16, 2016 at 21:27
  • 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. Commented Oct 16, 2016 at 21:40
  • Keywords: "given length". This would mean that your program is going to take some factor of n memory. Commented Oct 16, 2016 at 22:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. Do you know an approach with which I could solve this problem with constant space?
If you are trying to do it with variable-length strings, constant space is infeasible. The way Java works would prevent you from working on the String word you pass without making a copy, also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.