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('');
}
function reverseString(s: string): string {
return s.split('').reverse().join('');
}
def reverse_string(s: str) -> str:
return s[::-1]
<?php
function reverseString(string $s): string
{
return strrev($s);
}
class Solution {
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
}
More Basics problems
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy
- Make an Acronym · Easy