Reversing a string is one of the most frequently asked questions for programmers. You can even expect to see it during coding interviews. an interview may expect you know all the ways you can reverse a string excluding the built-in reverse function.
There are dozens of ways to reverse a string, so what are the best approaches? What best practices are these for reversing strings? Today, we’ll dive into those questions and explore how to reverse a string in three popular programming languages: C++, Javascript, and Python.
Today we’ll cover:
Get a detailed review of all the common data structures with implementations and visuals
Data Structures for Coding Interviews in Python
In programming, a string is a sequence of characters. It is one of the basic data types that we use to express text rather than numbers. Reversing a string means flipping the order of the characters completely. In other words, we are making the string read backwards.
Reversing a string has several uses for developers, though it is not that common in real-world scenarios. Sometimes, problems that involve regular expressions are easier to use or solve when the input string is reversed. In other cases, string reversal allows us to search and sort by the endings of strings.
The most common use of string reversal is in coding interviews. You can expect an interviewer to quiz you on string reversal without using a built-in function.
In coding challenges, you may see a question like this:
Reverse the string.
You may need to turn the string into an array.
Your result must be a string.
There are many ways to reverse a string in any programming language. The method you choose depends on the requirements of the program you are writing. Some languages have built-in functions or methods for string reversal, but you shouldn’t rely on them. There are dozens of approaches, and some of them are more effective than others:
We will take a look at all of these methods in detail and explore the best practices for string reversal. Let’s get started!
There are three steps involved in reversing a string in JavaScript: .split()
, .reverse()
, .join()
. You can remember it with the following formula:
.s.r.j("")
Let’s take the string "Hello!"
and reverse it using this formula. Here is a visual representation of the process.
In JavaScript, the split()
method will split a string into an array of substrings and return a new array. It does not change the original array.
var word = "Hello!";var splitWord = word.split("");
We have now created the following array of standalone characters:
['H', 'e', 'l', 'l', 'o', '!']
Now that we have our characters, we want to reverse them. We can use the reverse()
method , which reverses an array in place.
var reverseWord = splitWord.reverse();
The code above gives us teh following output:
['!', 'o', 'l', 'l', 'e', 'h']
So, now our characters are reverse, but it’s not a single string of characters anymore.
The last step is to rejoin those characters to form a single, reversed string. We can use the join()
method, which joins all elements of an array into one string.
joinedWords = reverseWord.join("")
The final output would be:
!olleH
You can put all your methods together on a single line:
var word = "Hello";var reverseWord = word.split("").reverse().join("");console.log(reverseWord);
Try it yourself with the code tabs using a string of your choice!
// Try it yourself here!
In C++, reversing a string means flipping changing the order of the characters so that it reads backwards. There are multiple implementations that can be used to reverse a string in C++. Let’s look at the four best approaches.
You can write a loop within the main
body of the function to reverse a string. In the loop body, you need to use the built-in swap
function, which will change element positions.
#include <iostream>using namespace std;int main() {string greeting = "Hello!";int len = greeting.length();int n=len-1;for(int i=0;i<(len/2);i++){swap(greeting[i],greeting[n]);n = n-1;}cout<<greeting<<endl;}
There may be a case where you aren’t allowed to use the built-in function, so we need to alter the code a bit.
#include <iostream>using namespace std;int main() {string greeting = "Hello!";int len = greeting.length();int n=len-1;for(int i=0;i<(len/2);i++){char temp = greeting[i];greeting[i] = greeting[n];greeting[n] = temp;n = n-1;}cout<<greeting<<endl;}
C++ has a built-in function for reversing a string. If you are allowed to use this, it is recommended for ease. We have two inputs for this function:
#include <iostream>//The library below must be included for the reverse function to work#include<bits/stdc++.h>using namespace std;int main() {string greeting = "Hello!";//Note that it takes the iterators to the start and end of the string as argumentsreverse(greeting.begin(),greeting.end());cout<<greeting<<endl;}
Learn data structures and algorithms for coding interviews without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
Data Structures for Coding Interviews in Python
Also available in C++ and JavaScript
If we cannot use any built-in function, we can write our own to reverse a string. This function will use recursion. Recursion is when a function is called within the same function. Take a look to see an example.
#include <iostream>using namespace std;void reverse_String(string& greet, int n,int i){if(n<=i){return;}swap(greet[i],greet[n]);reverse_String(greet,n-1,i+1);}int main() {string greeting = "Hello";cout<<"String before reversal: "<<greeting<<endl;reverse_String(greeting,greeting.length()-1,0);cout<<"String after reversal: "<<greeting<<endl;}
The last way to reverse a string in C++ without any built-in function is to create a new string. We will be looping backwards through our string and storing its elements in a new string of the same size using the push_back
method.
#include <iostream>using namespace std;int main() {string greeting = "Hello!";string new_greeting;for(int n = greeting.length()-1; n >= 0; n--){new_greeting.push_back(greeting[n]);}cout<<"Original string: "<< greeting << endl;cout<<"New reversed string: "<< new_greeting << endl;}
Now that we’ve seen the four ways to reverse a string in C++, try them out below using the code tabs. Explore the code from the examples above and get a bit of practice.
// Explore the loop approach here
In Python, strings are ordered sequences of characters. Unlike C++, there is no built-in method to reverse a string in Python. The following three methods are the best practices for reversing a string in Python.
We can use slicing to reverse a string. The slice()
function returns a slice object, which is used to specify how to slice a sequence of characters You can specify where to start and end the slicing.
We must create a slice that starts with the length of the string and ends at index 0.
stringname[stringlength::-1]
Or we can write it without specifying the string’s length.
stringname[::-1]
With the slice statement, we start with the string length, end at position 0, and move with the step -1 (which means one step backwards).
str="Hello!" # initial stringstringlength=len(str) # calculate length of the listslicedString=str[stringlength::-1] # slicingprint (slicedString) # print the reversed string
Similar to C++, we can use a loop to reverse a string. w can use wither a for
or while
loop. To start, let’s create a new array called reversedString[]
. We loop over the list with iterating variable index initialized with the length of the list. Take a look at the process:
str[index-1]
with reverseString
str = "Hello!" # initial stringreversedString=[]index = len(str) # calculate length of string and save in indexwhile index > 0:reversedString += str[ index - 1 ] # save the value of str[index-1] in reverseStringindex = index - 1 # decrement indexprint(reversedString) # reversed string
This technique takes advantage of Python’s iterator protocol. It will reverse a string using reverse iteration with the built-in reversed()
function that cycles through the elements in the string in reverse order and then uses .join()
to merge them into a eversed string!
The syntax for this method is as follows:
str="Hello!"
reversedstring=''.join(reversed(str))
Check it out in the code widget below.
str = 'Hello!' #initial stringreversed=''.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new stringprint(reversed) #print the reversed string
Now that we’ve seen the three best ways to reverse a string in Python, try them out below using the code tabs. Explore the code from the examples above and get a bit of practice.
# explore the Slicing method here
Congratulations! You now know the best practices for reversing a string in JavaScript, C++, and Python. These skills are bound to help your interview process. Be sure to keep practicing data structure, algorithms, and other common interview questions like:
Educative’s Data Structures for Coding Interviews is the definitive place to prepare for interviews. With courses in most popular programming languages, you’re bound to quickly master data structures through real-world problem solving. Get started today!
Happy learning!
Free Resources