Start learning free

LESSON 170 OF 347 · STRINGS

Reverse String in C#: O(n²) by Prepending Characters

Practice O(n2) Read the full explanation

Given a string, write a function that reverses that string without using built-in functions or libraries.

Example:

Input:  "hello"

Output: "olleh"

Note:

Your algorithm should run in O(n^2) time and use O(n) extra space.


STEP 1 OF 4
    Ctrl + Enter to check

    C# · STRINGS

    Reverse String in C#, explained

    Problem overview

    The method Reverse receives a string, input, and returns the same characters in the opposite order, without using built-in reversing helpers. For "hello" it returns "olleh", and for an empty string it returns an empty string.

    The statement allows O(n²) time and O(n) extra space. That budget is generous on purpose: it lets this lesson use the simplest possible idea, and a later lesson on the same problem reaches O(n).

    Approach: put each new character in front

    Read the input from left to right and build the result by placing every character at the front of what you have so far. Tracing "hello":

    after 'h':  "h"
    after 'e':  "eh"
    after 'l':  "leh"
    after 'l':  "lleh"
    after 'o':  "olleh"
    

    The first character read ends up last, and the last one ends up first, which is exactly a reversal.

    The price is in the copying. A C# string can't be changed after it is created, so character + reversedString allocates a new string and copies every character of the old one into it. The copies cost 1, 2, 3, ... up to n - 1 characters, which adds up to about n²/2, so the whole method is O(n²). This is the cost the statement permits. Appending to a StringBuilder, as the next lesson does, avoids it.

    Step by step

    1. Start with an empty result. reversedString begins as "", so an empty input falls straight through to the return.
    2. Loop over the characters. input.ToCharArray() copies the string into a char[], and foreach hands out one char at a time as character. Looping over input directly would also work, since a string is a sequence of char values.
    3. Prepend the character. Assign character + reversedString back to reversedString. Because one operand is a string, + joins text instead of adding numbers.
    4. Return the result once the loop has visited every character.

    The solution in C#

    class Solution {
        public string Reverse(string input) {
            string reversedString = "";
            foreach (char character in input.ToCharArray()) {
                reversedString = character + reversedString;
            }
            return reversedString;
        }
    }
    

    A few C# details are worth noticing:

    • char + string is concatenation. The result of joining a char and a string is a string. The trap is two characters: 'a' + 'b' adds their numeric codes and gives the int 195. Here one side is always a string, so the order of operands doesn't matter for the type.
    • The assignment is needed. A string never changes in place, so writing just character + reversedString; would compute a new string and discard it.
    • foreach variables are read-only. You can't assign to character inside the loop, which suits this solution.
    • Characters are UTF-16 code units. Letters such as é are one char, but an emoji takes two. Reversing code units would swap the halves of such a pair and corrupt it. The lesson's inputs are plain text, so this doesn't come up.

    Complexity

    Time: O(n²). The loop runs n times. In iteration k the concatenation copies the k characters built so far plus the new one, so the total number of character copies is roughly 1 + 2 + ... + n, about n²/2. Dropping the constant gives O(n²). The ToCharArray() call adds one O(n) pass, which doesn't change the result.

    Space: O(n). The character array holds n characters and the result grows to n. Each intermediate string becomes garbage after the next iteration, so only a few strings of length up to n exist at any moment.

    Edge cases and common mistakes

    • Empty string. The loop body never runs and the method returns "".
    • One character. "a" comes back unchanged.
    • Appending instead of prepending. reversedString + character rebuilds the original string.
    • Forgetting to assign back. Without reversedString = the result stays empty.
    • Using a different method name. The tests call Reverse, with a capital R, on a string parameter named input.

    Testing

    • "hello" gives "olleh".
    • "a" gives "a".
    • "" gives "".
    • "ab cd" gives "dc ba"; the space is just another character.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free