Goldman Sachs Interview Question
Senior Software Development EngineersCountry: United States
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();
}
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.
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"
private void reverseString(String strValue) {
List<String> lstWords = Arrays.asList(strValue.split(" "));
Collections.reverse(lstWords);
System.out.println(lstWords.toString().replaceAll(",", "").
replace("[", "").replace("]", ""));
}
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);
}
}
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--;
}
}
}
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);
}
}
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);
}
}
"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 " ".
String a = ActualStringValues;
String[] s = a.split(" ");
a = "" ;
for(String tmp : s){
a = tmp + " " + a;
}
a = a.trim();
System.out.println(a);
#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;
}
#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++;
}
}
}
#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++;
}
}
}
/*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;
}
//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;
}
}
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"));
}
}
#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;
}
This can be done without any additional space in 2 pass
- Varun April 11, 20131) reverse the string in place
2) reverse each word of the reversed string.