Interview Kickstart has enabled over 21000 engineers to uplevel.
Tech interviews are tough, especially if you’re gunning for FAANG and other tier-1 tech companies. Software engineers or developers are expected to be masters at data structures and algorithms. Moreover, depending on the role you’re applying for, you would also require expertise in specific programming languages such as Java or Python.
So while you are planning your prep, be sure to include the basics. In this article, we’re focussing on Java — specifically, how to reverse a string in Java. Here’s how we’ll cover it:
The string is basically a sequence of characters. In Java, a string is an object, and there are a number of operations we can perform on the string. As the name suggests, Reversing a string is nothing but flipping the given string — that is, the last letter becomes the first, the second-to-last letter becomes the second, and so on.
For example:
Input String: “InterviewKickstart”
Reversed String: “tratskciKweivretnI”
Input String: “12345”
Reversed String: “54321”
Input String: “Hello098”
Reversed String: “890olleH”
There are many ways to implement this; we’ll cover the following methods:
ChatAt method is used to access the character in a string at a particular index.
We create an empty string object first and then append the characters in that string. To append the characters, we first iterate over the original string from its last position and access the character in it by CharAt method. And hence our new string, which was empty, will now contain the reversed string of initial.
import java.util.*;
public class ReverseString {
public static void main(String args[]) {
// s1 will contain the initial string and rev will contain the string after reversing it.
String s1 = "InterviewKickstart", rev = "";
System.out.println("Initial String: " + s1);
int n = s1.length();
// iterating over the original string from right.
for (int i = n - 1; i >= 0; i--)
rev = rev + s1.charAt(i); // using CharAt() method to access character at particular index.
// printing the result
System.out.println("Reversed string: " + rev);
}
}
Time Complexity: O(n)
Space Complexity: O(n)
In this approach, we use the toCharArray method of string to convert it into a character array first. After converting the given string into a character array we just iterate the array from the last position and append the characters into an empty string similar to what we have done in method 1.
import java.util.*;
public class ReverseString {
public static void main(String args[]) {
// s1 will contain the initial string and rev will contain the string after reversing it.
String s1 = "InterviewKickstart", rev = "";
System.out.println("Initial String: " + s1);
int n = s1.length();
// converting string into character array
char c[] = s1.toCharArray();
// iterating over the array from right.
for (int i = n - 1; i >= 0; i--)
rev = rev + c[i];
// printing the result
System.out.println("Reversed string: " + rev);
}
}
Time Complexity: O(n)
Space Complexity: O(n)
In string buffer class, we have a built-in reverse() method, which can be used to reverse the string. This method takes in a string object as a parameter and returns the reversed string. We will use this in-built method in this approach to reverse the string.
import java.util.*;
public class ReverseString {
// This Function reverses the string in Java using StringBuilder
public static String rev(String s) {
// We are passing the string 's' in the constructor of StringBuilder to create a new object of StringBuilder Class. The string 's' will remain unchanged. toString() will return the object of the string class.
return new StringBuilder(s).reverse().toString();
}
public static void main(String args[]) {
// s1 will contain the initial string.
String s1 = "InterviewKickstart";
System.out.println("Initial String: " + s1);
// reversing the string using StringBuilder class
s1 = rev(s1);
// printing the result
System.out.println("Reversed string: " + s1);
}
}
Time Complexity: O(n)
Space Complexity: O(1)
getBytes() method of String is used to convert the string into bytes, and we will use this method to reverse the string. First, we’ll create a temporary byte array whose length will be equal to the length of the string, and then we’ll store the string in byte form in a reverse manner in that byte array. Now, we again convert it into the string and simply print it.
import java.util.*;
public class ReverseString {
public static void main(String args[]) {
// s1 will contain the initial string.
String s1 = "InterviewKickstart";
System.out.println("Initial String: " + s1);
byte[] tp = s1.getBytes();// converting string into bytes by using getBytes() method
// storing result in reverse order
for (int i = 0; i < tp.length / 2; i++) {
byte temp = tp[i];
tp[i] = tp[tp.length - i - 1];
tp[tp.length - i - 1] = temp;
}
// printing result by converting it into string.
System.out.println("Reversed string: " + new String(tp));
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Collection class in Java has a built-in reverse() method to reverse the object. In this method, we use the reverse() method and ArrayList object of Java to reverse the string. First, we add each of the string characters into the ArrayList object. We’ll pass this ArrayList object to the reverse() method to get it reversed. Then we iterate over the ArrayList and push all characters in StringBuilder. And then, by using the toString() method, we get our reversed string.
import java.util.*;
import java.util.Arrays;
import java.util.List;
public class ReverseString {
public static void main(String args[]) {
// s1 will contain the initial string.
String s1 = "InterviewKickstart";
System.out.println("Initial String: " + s1);
List<Character> a = new ArrayList<>(); // creating array list object
// adding characters into array list object
for (char c : s1.toCharArray()){
a.add(c);
}
Collections.reverse(a); // using inbuilt reverse method to reverse the list.
// convert in string
String res = “”;
// appending characters to the result string.
(Character c : a) {
res += c;
}
// printing result.
System.out.print("Reversed string: ");
// printing the string
System.out.println(res);
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Here are a few examples of the types of questions you can expect at tech interviews at FAANG and other tech companies,
For more tech interview questions and problems, check out the following pages: Interview Questions, Problems, Learn.
Question 1: What is StringBuilder in Java, and how is it different from String class?
Answer: StringBuilder is a class in Java. It represents a mutable sequence of characters. This class is similar to the String, but it is one of the alternatives to the String class. However, StringBuilder is faster than String. equals() method can be used to compare two Strings in Java. StringBuilder does not override the equals() So, this method can not compare two StringBuilder objects.
A new StringBuilder object cannot be created without using a new operator, while a String object can be. Length of the String object is fixed, while StringBuilder has a method setLength(), which can be used to change the length of its object.
Question 2: Why is the string immutable in Java?
Answer: Immutable string means we can not change the state of the object, but we can change the reference to the object. It simply means strings are unmodified. In Java, string objects are cached in the string pool, making strings immutable because we can’t directly change the objects. For example, when we use the += operator to append the string, it will create a new object each time because strings are immutable, and once they are created, they can’t be changed.
If you’re looking for guidance and help with getting your prep started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
----------
Article contributed Omkar Deshmukh
Attend our webinar on
"How to nail your next tech interview" and learn