Easy 0 solved 0% acceptance

Reverse a String

Return the characters of a string in reverse order.

What you'll learn

  • Walk through a string backwards
  • Build a new string from characters
  • Use slicing or two pointers

Problem

Reverse text so the last character comes first.

Implement reverse_string(text).

Input

text: The text to reverse.

Output

Return the reversed text.

Constraints

0 ≤ length ≤ 10,000

Examples

Example 1
Input:
text = "hello"

Expected output:
expected = "olleh"
Input:
std::string text = "hello";

Expected output:
std::string expected = "olleh";
Input:
string text = "hello";

Expected output:
string expected = "olleh";

Explanation

h-e-l-l-o read backwards is "olleh".

Example 2
Input:
text = "a"

Expected output:
expected = "a"
Input:
std::string text = "a";

Expected output:
std::string expected = "a";
Input:
string text = "a";

Expected output:
string expected = "a";

Explanation

A single character reversed is itself.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The answer is the characters in opposite order.

Hint 2

A two-pointer approach or a backward traversal both work well.

Hint 3

Be sure the empty string stays empty after reversal.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.