C# Programming Interview Questions Tutorial
C# Interview Question: Reverse String
In this interview question you are asked to reverse the characters of the string. There are many methods to to that, which is better depends on the time and space complexity of the program.
Method 1:
In this method we will use a new array to hold the reverse string and divide the source string array into half and then assign the last element of source string to first element of new string and first of source to last element of new array. This will reduce the loop time to half so it will be O(log n) which is good runtime complexity.
public string ReverseString(string str)
{
char[] charArr = new char[str.Length];
for (int i = 0, j = str.Length - 1; i <= str.Length / 2; i++, j--)
{
charArr[i] = str[j];
charArr[j] = str[i];
}
return new string(charArr);
}