Coding problem · Easy · Basics

Reverse a String

Easy Algorithms & data structures

Given a string s, return it reversed.

"hello" becomes "olleh".

Example 1

Input: s = "hello"
Output: "olleh"

Example 2

Input: s = "ReadyCamel"
Output: "lemaCydaeR"

Hints

Hint 1

Build a new string by reading the characters from the last one to the first.

Hint 2

Most languages can split a string into characters, reverse the list and join it back.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

Walk from the end to the start, or use the language's built-in reverse on a list of characters. Strings are immutable in most languages, so we build a new one.

Reference solution

function reverseString(s) {
  return s.split('').reverse().join('');
}

Was this page helpful?