Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: United States
public class ReverseOfAString {
public String reverse(String str) {
char[] string = str.toCharArray();
int len = string.length - 1;
int middleElement = len / 2;
for (int i = 0; i <= middleElement; i++) {
char temp = string[i];
string[i] = string[len - i];
string[len - i] = temp;
}
return new String(string);
}
public static void main(String argc[]) {
ReverseOfAString r = new ReverseOfAString();
String rev = r.reverse("INDIA");
System.out.println(rev);
}
}
Depends on the language. It sounds like Java/C#, so it's immutable.
Use StringBuffer/StringBuilder.
We are asked for a time efficient code, not a space efficient one. We can hence use another new string of same length as the given string. Then traverse the given string from right end and keep inserting the values in the new string in forward direction. Time complexity: O(n).
I don't know what they tested by asking this elementary question.
public class Y{
void reverse(String q)
{
StringBuffer b =new StringBuffer(q);
int len=b.length();
char temp;
for(int i=0;i<=len/2;i++){
temp= b.charAt(i);
b.setCharAt(i, b.charAt(len-i-1)) ;
b.setCharAt(len-i-1, temp);
}
System.out.println(b);
}
public static void main(String args[]){
Y y =new Y();
y.reverse("ABCDEFGHI");
}
}
public static String reverse(char[] string, int index){
if(index == string.length){
return "";
}else {
return reverse(string, index +1) + string[index];
}
}
CALL LIKE
reverse("JAVA IS FUN".toCharArray(),0)
I believe this is one of the better way if we consider performance.
However we can still do it in recursive way without converting into char array:
public static String reverseStr(String str, int index) {
if (index == str.length()) {
return "";
} else {
return reverseStr(str, index + 1) + str.charAt(index);
}
}
and this has slightly better performance as compared to above one. Try with System.nanoTime() to see the difference.
Swap first and last cells, second and second last cells, and so on till we reach the center
- bitflipper March 19, 2012