I have here some methods which reverse string characters. Example if given string is "HELLO", it will returns "OLLEH". Are my big o notation for these approaches correct? And which approach is the most efficient (both time and space complexity)?
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_TwoArrays(string str)
{
char[] arr2 = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
arr2[i] = str[str.Length - 1 - i];
}
return string.Join("",arr2);
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ClassicForLoop_ArrayIndex(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
{
sb.Append(str[i]);
}
return sb.ToString();
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ForEachConcat(string str)
{
string newStr = "";
foreach (var item in str)
{
newStr = item.ToString() + newStr;
}
return newStr;
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_Stack(string str)
{
var stack = new Stack();
foreach (var item in str) // Time Complexity: o(n)
{
stack.Push(item); // Time Complexity: o(1)
}
return string.Join("", stack.ToArray());
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ArrayReverse(string str)
{
char[] arrChar = str.ToCharArray();
Array.Reverse(arrChar);
return string.Join("", arrChar);
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_LINQ(string str)
=> string.Join("", str.Reverse());
O(n)
space. In order to getO(1)
space you would need to reverse the string in place which is not possible. \$\endgroup\$