Reverse a string
Reverse the characters in a string without calling Array.Reverse.
Course progress
Problem 6 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "BuildQuill"
Expected output
lliuQdliuB
What is happening?
Taking the characters from the last position back to the first changes BuildQuill into lliuQdliuB.
Solution strategy
Build the right mental model
Copy the immutable string into a character array, then swap the first and last characters while moving toward the center.
Core concepts
arrays · two pointers
Complexity
Time O(n), space O(n) for the character array.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for reverse-string
using System;
class Program
{
static string Reverse(string text)
{
char[] characters = text.ToCharArray();
int left = 0;
int right = characters.Length - 1;
while (left < right)
{
char temporary = characters[left];
characters[left] = characters[right];
characters[right] = temporary;
left++;
right--;
}
return new string(characters);
}
static void Main()
{
Console.WriteLine(Reverse("BuildQuill"));
}
}Knowledge check
Questions students often ask
What is the main idea behind reverse a string?
Copy the immutable string into a character array, then swap the first and last characters while moving toward the center.
What is the time and space complexity of this solution?
Time O(n), space O(n) for the character array.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.