Goldman Sachs Interview Question for Senior Software Development Engineers


Country: United States




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

This can be done without any additional space in 2 pass
1) reverse the string in place
2) reverse each word of the reversed string.

- Varun April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

actually it is easier to implement if you switch the two steps

- athans June 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Time: O(n)
Space: O(n)

private static String getReversedSequence(String input) {
		StringBuffer output = new StringBuffer();
		
		int end_index = input.length();
		for (int i = end_index - 1; i >= 0; i--) {
			char space = input.charAt(i);
			if (space == ' ') {
				output.append(input.substring(i + 1, end_index));
				end_index = i;
				output.append(' ');
			}
		}
		output.append(input.substring(0, end_index));
		return output.toString();
	}

- Anonymous April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

It is possible to do it in linear time and using constant space.

If you don't want to create a new string and just need to modify the one you have you can reverse characters in the string, and then reverse characters in each word.

If it is OK to create a new string you just need to go from the end of the original string and keep index of the end of the current word. And as soon as you reach any separate character simply copy each character from input string to output string from current index to word's end index and update word's end index.

- J. April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 3 vote

Push all the words in a stack and then pop the all out.

- alex April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Simple but not optimized. Can be done in place without O(n) memory.

- Karthik April 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

if we follow your stack approach then for the input "Today is Wednesday" we get output as "yadsendeW si yadoT" but instead we need output as "Wednesday is Today"

- Gaurav June 10, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

he is saying to push words in stack not individual characters ,....
he's right .

- coderpec August 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

private void reverseString(String strValue) {
		
		List<String> lstWords = Arrays.asList(strValue.split(" "));
		Collections.reverse(lstWords);
		System.out.println(lstWords.toString().replaceAll(",", "").
				replace("[", "").replace("]", ""));
	}

- rizwan.amd April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Simple and nice

- Naruto August 24, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

import java.util.Scanner;
class demo
{
public static void main(String g[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the String");
String s1 = s.nextLine();
String s2 ="";
		
		int end_index = s1.length();
		for (int i = end_index - 1; i >= 0; i--) {
			char space = s1.charAt(i);
			if (space == ' ') {
				s2 = s2 + s1.substring(i + 1, end_index);
				end_index = i;
				s2 = s2 + " ";
			}
		}
		s2 = s2 + s1.substring(0, end_index);;
		System.out.println(s2);
}
}

- shekhawat.amit1019 April 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Guessing it in java:

String str = input; 
String str2 = "";
int lastIndexOfSpace = lastIndexOf(" ");
while (lastIndexOfSpace > 0){
	if (lastIndexOfSpace < length(str) - 1)
		str2 += str.substring(lastIndexOfSpace + 1) + " ";
	str = str.substring(0, lastIndexOfSpace);
}

- Anonymous April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse(str):
s=str.split(" ")
s.reverse()
for i in s:
print(i end = " ")

- Anonymous April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x='Today is Wednesday'.split()
x.reverse()
' '.join(x)
print x

- Shaan April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This can be done in linear time.First reverse the sentence and then reverse the individual words.

Code:

public class ReverseSentence {
	public static void main(String[] args) {
		String a = "Today is Wednesday";
		a = a.trim();
		char[] cArr = a.toCharArray();
		ReverseSentence r = new ReverseSentence();
		r.reverse(cArr, 0, cArr.length-1);
		int s = 0;
		for (int i = 0; i < cArr.length; i++) {
			if (cArr[i] == ' ') {
				r.reverse(cArr, s, i - 1);
				s = i + 1;
			}
		}
		//call for the last word in the sentence
		r.reverse(cArr, s, cArr.length-1);
		System.out.println(cArr);
	}

	public void reverse(char c[], int i, int j) {
		char t;
		while (i < j) {
			t = c[i];
			c[i] = c[j];
			c[j] = t;
			i++;j--;
		}
	}
}

- Dhass April 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void reverseSentence(String insentence) {
	char[] sentence = insentence.toCharArray();
	int[] blankposlist = new int[100];

	displayArray(sentence);
	int k = 0;
	blankposlist[k++] = -1;

	// storing the position of blank space in the input string.
	for (int i = 0; i < sentence.length; i++) {
	    if (sentence[i] == ' ') {
		blankposlist[k++] = i;
	    }
	}
	blankposlist[k] = sentence.length;
	// reverse the input string
	reverseString(sentence, 0, sentence.length - 1);

	// Reverse each word
	for (int m = 0; m < sentence.length;) {
	    int reverselen = blankposlist[k] - blankposlist[k - 1] - 1;
	    reverseString(sentence, m, m + reverselen - 1);
	    m = m + reverselen + 1;
	    k--;
	}

	displayArray(sentence);
    }

 public void reverseString(char[] inarray, int start, int end) {
	char ch;
	for (int i = 0; i <= (end - start) / 2; i++) {
	    ch = inarray[start + i];
	    inarray[start + i] = inarray[end - i];
	    inarray[end - i] = ch;
	}
    }

void displayArray(char[] inarray) {
		System.out.println("\n---- Displaying array ---");
		for (char element : inarray) {
			System.out.print(element);
		}
	}

- Rudra April 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StrRev {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String sentence = "God is Great";
		StringBuffer sbuf = new StringBuffer();
		String[] s = sentence.split(" ");
		for(int i=0; i<s.length; i++)
		{
			sbuf.append(s[s.length-i-1]).append(" ");
		}
			System.out.println("str buf = " + sbuf);
	}

}

- Guest April 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void revString(String str){
		 
		 StringBuffer sb = new StringBuffer();
		 String s[] = str.split(" ");
		 int len = s.length;
		 
		 for(int i=0; i< len; i++)
		 {
			 sb.append(s[len-i-1]);
			 if(i!=len-1)
			 {
				 sb.append(" ");
			 }
			 
		 }
		 
		 System.out.println(sb);		 
		 
	 }

- Anonymous April 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Guys,
I forgot to mention that I was supposed to use any "in-built String functions such as String.split(), String.Reverse(),etc"

- xankar April 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

"Sathyaa blackhat" has the answer here:

stackoverflow.com/questions/4705069/c-program-on-reversing-a-sentence

Steps
1) Create a Reverse(start,end) method which reverses chars from start to end.
2) Then do Reverse (start, strlen-1). Reverse the whole string.
3) Then Reverse words by adjusting pointers until you encounter " ".

- xankar April 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String a = ActualStringValues;
String[] s = a.split(" ");
a = "" ;
for(String tmp : s){
a = tmp + " " + a;
}
a = a.trim();
System.out.println(a);

- Harish Arora May 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nice. Simplest java approach.

- Kb June 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <string.h>


int main()
{
char str[] = "Today is wednesday";
char * temp;
char * revStr[5] = {NULL};
int strCnt = 0;

temp = strtok(str," ");

while(temp)
{
revStr[strCnt] = temp;
strCnt++;
temp = strtok(NULL," ");
}

while(strCnt--)
{
printf("%s ",revStr[strCnt]);
// strCnt--;
}

return 0;
}

- Anonymous June 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i,j=0,k=0;
char sent[100],sent2[10][10];
gets(sent);
for(i=0;sent[i]!='\0';i++)
{

if(sent[i] == ' ')
{
sent2[j][k] = '\0';j++;k = 0;i++;
}
sent2[j][k] = sent[i];
k++;
}
sent2[j][k] = '\0';i=0;
for(k=j;k>=0;k--)
{
while(1)
{
if(sent2[k][i] == '\0')
{
printf(" ");i=0;break;
}
printf("%c",sent2[k][i]);i++;
}
}

}

- Anonymous June 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	int i,j=0,k=0;
	char sent[100],sent2[10][10];
	gets(sent);
	for(i=0;sent[i]!='\0';i++)
	{
		
		if(sent[i] == ' ')
		{
			sent2[j][k] = '\0';j++;k = 0;i++;
		}	
		sent2[j][k] = sent[i];
		k++;
	}
	sent2[j][k] = '\0';i=0;
	for(k=j;k>=0;k--)
	{
		while(1)
		{
			if(sent2[k][i] == '\0')
			{	
				printf(" ");i=0;break;
			}
			printf("%c",sent2[k][i]);i++;
		}				
	}
	
}

- Anonymous June 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
String str= " REVERSE THE STRING";

int lenght=str.length();
int subsi=0;
StringBuilder strB= new StringBuilder();
for (int i= lenght-1; i>=0;i--){

subsi++;
if(str.charAt(i)==' '){
String subs=str.substring(i,i+subsi );
strB.append(subs);
subsi=0;
}
}
}

- Lokesh Chouhan June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String input = "Today is Wednesday";
		String output = "";
		String[] st = input.split(" ");
		for(int i = st.length; i>0; i--) {
			output += st[i-1] + " ";
		}
		System.out.println(output);
	}

- King007 June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*Write a program to reverse the sequence of words in a sentence. 

	For Eg: 
	String str = "Today is Wednesday"; 

	Output: 
	String str2 = "Wednesday is Today"*/
	public static String reverse(String s){
		//Step 1 do the null check
		// Step 2 empty string "". is handeled
		String [] str = s.split(" "); 
		String result =""; 
		for(int j=str.length-1;j>=0;j--){
			if(j!=0)
			result += str[j]+" ";
			else
			result += str[j];
		}
		return result;
	}

- Malleswara Dyamappa July 10, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Working C++ Code

void ReverseWords(char word[] )
{
int counter=0;
int counter_space = 0 ;
int counter_laenge=0;
int zeiger = 0 ;
char arr [10];
bool index = false ;
int k = 0 ;
int length = 0;

for(int i = 0 ; word[i];i++) counter_laenge ++;
for(int i = 0 ; word[i];i++)
{
if(word[i] == 32) counter ++;
}

for(int t = 0; t<counter ; t++)
{

for(int j= 0 ; word[j];j++)
{
if(!index)
{
if(word[j] == 32 ) counter_space ++;
if(counter_space == counter )
{
index = true;
}
}
else
{
arr[k] = word[j];
k++;
length++;
}
}

arr[k] = 0;

//Shift takes place here
for( int r = counter_laenge; r > length+zeiger; r--)
{
word[r-1] = word[r-length-2];
}

for( int l=zeiger,z=0; arr[z];z++,zeiger++)
{
word[zeiger] = arr[z];
}

word[zeiger] = 32;
zeiger++;
index = false;
length = 0;
k=0;
counter_space=0;
}
}

- Schedl July 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class ReverseWords {

	public static String reverseWords(String input){
		List<String> out = Arrays.asList(input.split(" "));
		Collections.reverse(out);
		StringBuffer output = new StringBuffer();
		for (String s : out){
			output.append(s + " ");
		}
		return output.toString();
	}
	public static void main(String[] args) {
		System.out.println(ReverseWords.reverseWords("Today is Wednesday"));
	}

}

- Anonymous September 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <stdio.h>

using namespace std;

void doReverse(char *pszStr, int sIdx, int eIdx) {
	while (sIdx < eIdx) {
		char cTmp = pszStr[sIdx];
		pszStr[sIdx] = pszStr[eIdx];
		pszStr[eIdx] = cTmp;
		sIdx++; eIdx--;
	}
}

void doReverseOfSentence(char * csMsg) {
	int nLen = strlen(csMsg);
	doReverse(csMsg, 0, nLen - 1);

	int i = 0, sIdx = 0;
	while (i <= nLen) {
		if (csMsg[i] == ' ' || csMsg[i] == '\0') {
			doReverse(csMsg, sIdx, i - 1);
			sIdx = i + 1;
		}
		i++;
	}
}

int main() {
	char csMsg[] = "Today is Saturday";

	cout << "original string: " << csMsg << endl;
	doReverseOfSentence(csMsg);
	cout << "afterwarth string: " << csMsg << endl;
	getchar();
	return 0;
}

- Passerby_A February 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C# we can do this

var converse="Today is wednesday";
			
		for(int i=converse.Split(' ').Length-1;i>=0;i--)
		{
			Console.Write(converse.Split(' ')[i].ToString().Insert(0," "));
			
		}

- smartaquarius September 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

reverse words in a string :writeulearn.com/reverse-words-string-donot-reverse-word-letters/

- Anonymous January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

reverse words in a string :writeulearn.com/reverse-words-string-donot-reverse-word-letters/

- bhupesh January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

reverse words in a string :writeulearn.com/reverse-words-string-donot-reverse-word-letters/

- bhupesh January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

reverse words in a string :writeulearn.com/reverse-words-string-donot-reverse-word-letters/

- bhupesh January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void reverseStatement(String s){
String a[] = s.split(" ");
int l=0;
int h = a.length-1;
while(l<h){
String temp = a[h];
a[h] = a[l];
a[l]=temp;
l++;
h--;
}
}

- rathor.rajeev August 20, 2016 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More