## Salesforce Interview Question for Interns

Team: Quality Engineer Intern
Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public class StringReverse {
String str = "";
public StringReverse(String str){
this.str = str;
}
public String reverse() {
String[] strings = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = strings.length-1; i >=0 ; i--) {
sb.append(strings[i] + " ");
}
return sb.toString();
}

public static void main(String[] args) {
StringReverse sr = new StringReverse("I am in the river");
String str = sr.reverse();
System.out.println(str);
}

}``````

Comment hidden because of low score. Click to expand.
1
of 1 vote

This will leave a space at the end of the reversed string. We can solve it by either trimming it at the end.

Comment hidden because of low score. Click to expand.
0

String word = " i am bad . ";
char[] a = word.toCharArray();
StringBuffer sb = new StringBuffer();
int i = a.length - 1;
int j = a.length - 1;
int temp;
System.out.print("'");
while(i>=0)
{
if(a[i] != ' ') {
i--;
}
else{
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print(a[i]);
i--;
j=i;
}
}

temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print("'");
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

What if we don't have to use the inbuilt split function

Comment hidden because of low score. Click to expand.
0

Without the built-in split function, I would solve it recursively:

``````import java.util.ArrayList;

public class StringReverse {
String str = "";

public StringReverse(String str) {
this.str = str;
}

//first reverse the string and save in an arraylist.
//use the string builder to append them altogether.
public String reverse(){
ArrayList<String> res = reverseAndSplit(this.str);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < res.size(); i++) {
sb.append(res.get(i) + " ");
}
return sb.toString();
}

//Find the first space and save the word before that in beforeSpace.
//Reverse the string after the first space recursively.
//append beforeSpace to the end of array.
public ArrayList<String> reverseAndSplit(String str) {
str = str.trim();
if (str.indexOf(' ') == -1) {
ArrayList<String> res = new ArrayList<String>();
return res;
} else {
String beforeSpace = str.substring(0, str.indexOf(' '));
ArrayList<String> res = reverseAndSplit(str.substring(str
.indexOf(' ') + 1));
return res;
}
}

public static void main(String[] args) {
StringReverse sr = new StringReverse("I am in the river");
String str = sr.reverse();
System.out.println(str);
}

}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

First, I reverse the whole string: "I am bad" -> "dab ma I"
Then I reverse each word: "dab ma I" -> "bad am I"

Code may look like this:

``````// reverse word order in a sentence:
// NNN

#include <iostream>
#include <string>
using namespace std;

string reverseStr(string S, int u, int v){
for(int i = 0; i<(v-u+1)/2;i++){
swap(S[u+i],S[v-i]);
};
return S;
};

string reverseSentence(string S){
int st=0, ed=0;
int len = S.length();
S = reverseStr(S,0,len-1);
while(st<len-1){
while((st<len) and (S[st] == ' ')) st++;
ed = st;
while((ed<len) and (S[ed] != ' ')) ed++;
ed--;
//cout <<st<<" "<<ed<<endl;
S = reverseStr(S,st,ed);
//cout <<S<<endl;
st = ed+1;
};
return S;
};

int main()
{
string sentence = " This is a sentence with  multiple spaces  .  1 22 333 4444  ";
string reversed = reverseSentence(sentence);
cout <<"Original sentence:["<<sentence<<"]\n";
cout <<"Reversed sentence:["<<reversed<<"]\n";
return 0;
}``````

Comment hidden because of low score. Click to expand.
0

If the space looks ugly then trim them all first.

Comment hidden because of low score. Click to expand.
0
of 0 vote

What about if we use stack (LIFO).

``````import java.util.Stack;

public class WordsReversed {
private String reverse(String str) {
Stack<String> stack = new Stack<String>();
String temp = "";
while(true) {
if(str.indexOf(' ') > 0) {
temp = str.substring(0, str.indexOf(' '));
str = str.substring(temp.length()+1, str.length());
stack.push(temp.trim());
}
else {
stack.push(str.trim());
break;
}
}
str = "";
while(!stack.empty())
{
str = str + stack.pop() + " ";
}
return str;
}
public static void main(String[] args) {
WordsReversed wr = new WordsReversed();
String string = "I love programming";

System.out.println(wr.reverse(string));
}

}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public static String reverseWords(String s)
{
String[] sa = s.split(" ");
StringBuilder sb = new StringBuilder();

for (int i=sa.length-1; i>=0; i--)
{
sb.append(sa[i]);
}
int counter = 0;
for(int i=s.length()-1;i>=0; i--)
{
if(s.charAt(i) == ' ')
{
sb.insert(counter, " ");
}
counter++;
}

return sb.toString();
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<stack>
using namespace std;
int main()
{

char gg[] = "i am good test it";
char *ptr = NULL;
stack<string> stac;
ptr = strtok(gg," ");
while(NULL != ptr)
{
stac.push(ptr);
//cout<<" "<<ptr<<endl;
ptr = strtok(NULL," ");
}

while(!stac.empty())
{
cout<<stac.top()<<endl;
stac.pop();
}

getchar();
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include<stdio.h>
//To reverse the words of a string using stack
using namespace std;

void rev(char t[],int k)//used to reverse the string stored in stack
{

for(int i=k-1;i>=0;--i)
cout<<t[i];
cout<<" ";
}

void reverse(char a[])
{
char stack[200],t[40];
int top=-1,k;
for(int i=0;a[i]!='\0';++i)//used to store the string in stack
stack[++top]=a[i];

for(int i=top;i>=0;)//used to find the substring till we find space as delimiter
{
k=0;
for(int j=i;j>=0;--j)
{
if(stack[j]==' ')
break;
else
t[k++]=stack[j];
}
rev(t,k);
i=i-(k+1);
}

}

int main()

{
char ch;
char a[100];
cout<<"\nEnter the string:";
gets(a);
cout<<"\nReverse sentence:";
reverse(a);
cin>>ch;
return 0;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi, what was the single test case you came up with? Please let me know. Thanks!

Comment hidden because of low score. Click to expand.
0

Each word that is very long (1000s of characters). Your normal code will wok for empty string or one word, but with very long string, I think it will test memory, buffer overflow, performance, etc.

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public String Reverse(String given)
{
String toReturn;
String [] split = given.split("\ ");
for(int i=split.length-1;i>=0;i--)
{
return +=split[i];
return += " ";
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````#include<stdio.h>
#include<string.h>
int main()
{
printf("enter a string\n");
char *str;
str=(char*)malloc(50*sizeof(char));
fgets(str,50,stdin);
int ii=0,i=0;
char *arr=(char*)malloc(10*sizeof(char));
int j=0;
int k;
while(str[ii++]!='\n');
for(i=ii-2;i>=0;i--)
{
if(str[i]!=' ' )
{
arr[j++]=str[i];
}
else
{
for(k=j-1;k>=0;k--)
{
printf("%c",arr[k]);
}
printf(" ");
j=0;
}
if (i==0)
{
for(k=j-1;k>=0;k--)
{
printf("%c",arr[k]);
}
}

}
system("pause");
return 0;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````function reverseString(str) {
str = str.split(" "), result = "";
for(var i = str.length-1; i >= 0; i--) {
result += str[i] + " ";
}
return result;
}

reverseString("I am good"); // good am I``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string s;int n,i,j;char *c1;
cout<<"enter a string\n";
gets(c1);
s=c1;
n=s.length();
char c[n];
for(i=n-1,j=0;i>=0;i--,j++)
c[j]=s.at(i);
c[j]='\0';
s=c;
cout<<"\nreversed string is \n";
cout<<s;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string s;int n,i,j;char *c1;
cout<<"enter a string\n";
gets(c1);
s=c1;
n=s.length();
char c[n];
for(i=n-1,j=0;i>=0;i--,j++)
c[j]=s.at(i);
c[j]='\0';
s=c;
cout<<"\nreversed string is \n";
cout<<s;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

private String reverseInputString ( String inputStrting ) {
String[] inputArray = inputStrting.split (' ');
String resultString = '';
for ( integer i = inputArray.size()-1; i >= 0 ; i-- ) {
resultString = resultString+ inputArray[i]+' ';
}
return resultString ;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````void reverse(char *str)
{
char *temp ;
temp = (char*)malloc(sizeof(char)*strlen(str));
if(str==NULL)
return;
int len= strlen(str);
if(len==0 || len==1)
return;
int i=0;
int j=0;
int c=0;
for(j=len-1; j>0; j--)
{
if(*(str+j)==' ')
{

for(c=j+1;c<len;c++,i++)
{
*(temp+i)=*(str+c);
if(*(str+c)==' ')
break;
//i++;
}
*(temp+i)=' '; i++;
}
}
for(c=0;(*(str+c)!=' ');c++,i++)
{
*(temp+i)=*(str+c);
}
*(temp+i)='\0';
printf("%s",temp);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseSentance {

public String reverseMe(String reverseme) {

String sentance = reverseme;
String[] words = sentance.split(" ");
String tmp = "";

for (int i = words.length - 1; i >= 0; i--) {
tmp = tmp + " " + words[i];
}
return tmp.trim();
}

public static void main(String[] args) {
ReverseSentance rev = new ReverseSentance();
System.out.println(rev.reverseMe("I am good"));
}

}

Comment hidden because of low score. Click to expand.
0
of 0 vote

public String getReversedStringWithoutSplit(String inputs, Boolean reverseWord){
String singleString = "";
String result = "";
for(int i= inputs.toCharArray().length -1; i>=0; i--) {
singleString += inputs.toCharArray()[i];
if(inputs.toCharArray()[i] == (char)32 && reverseWord){
result += getReversedStringWithoutSplit(singleString.trim(), false) + " ";
singleString = "";
}
}
return reverseWord ? result += getReversedStringWithoutSplit(singleString, false):singleString;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

public String getReversedStringWithoutSplit(String inputs, Boolean reverseWord){
String singleString = "";
String result = "";
for(int i= inputs.toCharArray().length -1; i>=0; i--) {
singleString += inputs.toCharArray()[i];
if(inputs.toCharArray()[i] == (char)32 && reverseWord){
result += getReversedStringWithoutSplit(singleString.trim(), false) + " ";
singleString = "";
}
}
return reverseWord ? result += getReversedStringWithoutSplit(singleString, false):singleString;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

If we can use inbuilt functions, then its as easy as this in Python

``````a = "I am good"

for string in a.split(' ')[::-1]:
print string,``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = 'I am good';
var b = a.split(' ').reverse().join(' ');

console.log(b)

Comment hidden because of low score. Click to expand.
0
of 0 vote

If spaces can be considered to mark end and start for words --

``````/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("reverse of i am will - " + reverseWords("i am will"));
}

public static String reverseWords(String str){
String newString = "";
String arr[] = str.split(" ");
for(int i = arr.length-1; i >= 0; i--){
newString = newString  + " " +  arr[i];
}
return newString;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````private reverseString(){
String word = "  i am   bad  .  ";
char[] a = word.toCharArray();
StringBuffer sb = new StringBuffer();
int i = a.length - 1;
int j = a.length - 1;
int temp;
System.out.print("'");
while(i>=0)
{
if(a[i] != ' ') {
i--;
}
else{
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print(a[i]);
i--;
j=i;
}
}

temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print("'");``````

}

Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Stack;
import java.util.StringTokenizer;

public class Main {
public static String reverse_word(String s) {
StringTokenizer st = new StringTokenizer(s);
Stack<String> sk = new Stack<String>();
while (st.hasMoreTokens()) {
sk.push(st.nextToken());
}
String rs = "";
while (!sk.isEmpty()) {
rs += sk.pop() + " ";
}
return rs.trim();
}

public static void main(String[] args) {
String s = "I am no good";
System.out.println("Before: " + s);
System.out.println(" After: " + reverse_word(s));
}

/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}

}

Comment hidden because of low score. Click to expand.
0
of 0 vote

C# Solution

``````public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}

var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append(\$"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}

var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append(\$"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}

var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append(\$"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

C# Solution

``````public static string ReverseByWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}

var charIndex = input.Length - 1;
var returnValue = new StringBuilder();
var currentWord = string.Empty;
while (charIndex >= 0)
{
if (input[charIndex] != ' ')
{
currentWord = currentWord + input[charIndex];
}
if (input[charIndex] == ' ' || charIndex == 0)
{
//complete the word in reverse string.
var counter = currentWord.Length - 1;
while (counter >= 0)
{
returnValue.Append(currentWord[counter]);
counter--;
}
currentWord = "";
if (charIndex != 0)
{
returnValue.Append(" ");
}
}
charIndex--;
}
return returnValue.ToString();
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public static void main(String[] args) throws IOException {
String abc = "I am good";
String reverse = "";
String[] array = abc.split(" ");

for(int i=array.length-1;i>=0; i--)
{
reverse = reverse + array[i	] +" ";
}

System.out.println(reverse);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) throws IOException {
String abc = "I am good";
String reverse = "";
String[] array = abc.split(" ");

for(int i=array.length-1;i>=0; i--)
{
reverse = reverse + array[i ] +" ";
}

System.out.println(reverse);
}

Comment hidden because of low score. Click to expand.
-1
of 1 vote

package questions;
import java.lang.Exception;

public class Sf_Practice {

public static void main(String[] args) {
// Testcases
String []arr = {""," ","a", "aabb", "132!!@@@##!!", "aswbsdwwAQQQ", " hello how are you !! :) "};

for (int i = 0; i < arr.length; i++) {
try {
String res = reverseStrings(arr[i]);
System.out.println(res);
} catch (Exception e) {
if (e.getMessage().equals("Empty String !!!") ) {
System.out.print("Exception caught :)\n");
} else {
e.printStackTrace();
}
}

}
}

// reverse Strings method.
public static String reverseStrings(String s) throws Exception {
if (s.isEmpty()) {
throw new Exception("Empty String !!!");
}

if (s.length() <= 1) {
return s;
} else {
String reverse = "";
int cnt = s.length();
do {
cnt--;
String tmp = Character.toString(s.charAt(cnt));
reverse = reverse + tmp;

} while (cnt != 0);

return reverse;
}
}
}

Comment hidden because of low score. Click to expand.
-1
of 1 vote

Exception caught :)

a
bbaa
!!##@@@!!231
QQQAwwdsbwsa
): !! uoy era woh olleh

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.