Reverse a string in place
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (2167)

Write a function to reverse a String in place without creating another String.


Posted Answers


  • Create a character array from the input String.
  • Take two pointers at the first and last index of the array. Interchange their values.
  • Move the pointers - the first one in forward direction and the second one in backward direction.
  • Repeat the last two steps while the first pointer is less than the second pointer.

Example - Let the input string be '\( algoqueue \)'.



Time complexity = \( O(n) \).

public string reverseString(String input){

/* Input string is null */
if (input == null)
return null;

/* string to character array */
char[] string2CharArray = input.ToCharArray();
/* First pointer */
int firstIndex = 0;
/* Second pointer */
int lastIndex = input.length - 1;

while (firstIndex < lastIndex){

/* Exchange the values at the two pointer */
char temp = string2CharArray[firstIndex];
string2CharArray[firstIndex] = string2CharArray[lastIndex];
string2CharArray[lastIndex] = temp;

/* Move the first pointer forward */
firstIndex ++;
/* Move the second pointer backward */
lastIndex --;
}
return String.valueOf(string2CharArray);
}

You need to Sign In to post your solution.