N/A Interview Question for Software Engineer in Tests


Country: India
Interview Type: Phone Interview




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

So there are multiple spaces in the input string, but here is not getting displayed and are trimmed.

- qe.expert March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

public static void main(String[] args) {
// TODO Auto-generated method stub

String str = "This is a test String!!";

String temp[] = str.split(" ");
String result = null;
for(int i=1; i<=temp.length;i++){
String tempVar = null;
if(i%2 == 0){
for(int j = temp[i-1].length() - 1; j>=0; j--){
tempVar = tempVar + temp[i-1].charAt(j);
}
}

else if(i%2 != 0 || i == 0)
tempVar = temp[i-1].toUpperCase();

result= result + tempVar+" ";

}

System.out.println(result.replace("null", ""));

}

- Monark Arora June 11, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Pretty Straight forward:

public String modify(String orig) {
	
	String[] toModify = orig.split(" ");
	StringBuffer out = new StringBuffer();

	for (int i = 0; i < toModify.length; i++) {

		out.append( (stringIsOdd(toModify[i])) ? capitalize(toModify[i]) : reverse(toModify[i]) );
		out.append(" ");
	}

	return out.toString();
}

public String capitalize(String s) {
	
	return s.toUpperCase();
}

public String reverse(String s) {
	
	StringBuffer out = new StringBuffer();

	for (int i = 0; i < out.length(); i++) {

		out.append(s.charAt(out.length() - i - 1));
	}

	return out.toString();
}

public boolean stringIsOdd(String s) {
	
	return (s.length() % 2 == 1);
}

- SK March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C Code to solve the above problem is as follows

#include <stdio.h>
#include <ctype.h>

int main()
{
 char s[10000];
 char *p,*q;
 gets(s);
 p=s; q=s;
 int count=1;
 while(*p && *q){
if(*q==' '){
q++;
printf(" ");
p=q;
count++;
continue;
}
if(count%2==1){
if(!isupper(*q))
{*q=*q-32;
printf("%c",*q);}
q++;
}
else{
while(*q!=' ' && *q)
q++;
char *preserve=q;
q--;
while(q!=p){
printf("%c",*q);
q--;
}
printf("%c",*q);
q=preserve;
}
 }
    return 0;
}

- gowtham kesa March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Odd_upper_even_rev {
	public static void main(String args[]){
		String str="This is a test string!!";
		String finalstr="",arr[]=str.split(" ");
		int len=arr.length;
		for(int i=0;i<len;i++)
		{
			if(i%2==0)
			{
				arr[i]=arr[i].toUpperCase();
				
			}
			else
			{
				StringBuffer sb=new StringBuffer(arr[i]);
				StringBuffer temp=sb.reverse();
				String s=new String(temp);
				arr[i]=s;
				
			}
		}
		for(int j=0;j<len;j++)
		{
			finalstr=finalstr+" "+arr[j];
		}
		System.out.println(finalstr);
        		
	}

}

- faisal March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Bug.. this routine adds a space to the beginning of the string.

- Jim March 18, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Odd_upper_even_rev {
	public static void main(String args[]){
		String str="This is a test string!!";
		String finalstr="",arr[]=str.split(" ");
		int len=arr.length;
		for(int i=0;i<len;i++)
		{
			if(i%2==0)
			{
				arr[i]=arr[i].toUpperCase();
				
			}
			else
			{
				StringBuffer sb=new StringBuffer(arr[i]);
				StringBuffer temp=sb.reverse();
				String s=new String(temp);
				arr[i]=s;
				
			}
		}
		for(int j=0;j<len;j++)
		{
			finalstr=finalstr+" "+arr[j];
		}
		System.out.println(finalstr);
        		
	}

}

- faisal March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Odd_upper_even_rev {
public static void main(String args[]){
String str="This is a test string!!";
String finalstr="",arr[]=str.split(" ");
int len=arr.length;
for(int i=0;i<len;i++)
{
if(i%2==0)
{
arr[i]=arr[i].toUpperCase();

}
else
{
StringBuffer sb=new StringBuffer(arr[i]);
StringBuffer temp=sb.reverse();
String s=new String(temp);
arr[i]=s;

}
}
for(int j=0;j<len;j++)
{
finalstr=finalstr+" "+arr[j];
}
System.out.println(finalstr);

}

}

- Erfaisal54 March 18, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) solution in python:

def format_words(statement):
    words = statement.split(" ")
    output = []
    for word in words:
        if len(word)%2 == 0:
            x = ""
            for i in range(len(word) - 1, -1, -1):
                x += word[i]
            output.append(x)
        else:
            output.append(word.upper())
    for word in output:
        print "{}".format(word),

Due to the constraint that all chars in the input string may need alteration,
we are stuck with having to assume that a string like

"abcd efgh ijkl mnop qrst uvwx yz" would have to reverse every word in the input and
take O(n) time where n is number of chars total in the string.

A constant space solution would simply reassign the statement to a array of words split by spaces,
then operate on each word, with reversals being done in-place.

- Javeed March 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

while your code is correct, it is definitely not O(n). If you note carefully, you have a nested 'for'. Due to this, your actual performance is O(n**2).

- iceman June 11, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String convert(String target) {
		char [] chs = target.toCharArray() ;
		int count = 0 ;
		int j = 0 ;	    
	    for (int i = 0 ; i <= chs.length ;++i) {	    	
	    	if (i == chs.length || i > 0  && (chs[i] == ' ' || !Character.isLetterOrDigit(chs[i])) && Character.isLetterOrDigit(chs[i - 1])) {
	    		while (j < chs.length && !Character.isLetterOrDigit(chs[j])) {
	    			j++;
	    		}
	    		if (j <= i) {
	    			if (count % 2 == 0) {
	    				toUpper (j, i - 1 , chs);
	    			} else {
	    				reverse (j, i - 1, chs) ;
	    			}
	    			j = i ;
	    			count++;
	    		}
	    	}
	    }
	    
	    return  new String (chs) ;
	}
	
	private void reverse (int i , int j , char [] chs){
		for (; i < j ; ++i , --j) {
			char tmp = chs[i] ;
			chs[i] = chs[j] ;
			chs[j] = tmp ;
		}
	}
	
	private void toUpper (int i , int j , char [] chs) {
		for (int n = i ; n <= j ; ++n) {
			chs[n] = Character.toUpperCase(chs[n]) ;
		}

}

- Scott March 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var inString = "This is a test String!!";
var outString = "";

//Split
var tokens = inString.split(' ');

//Iterate
var alternator = false;
for(var i = 0; i < tokens.length; i++){

    var word;

    if(!alternator){
        word = capitalize(tokens[i]);
        outString = build(outString, word);
        alternator = !alternator;
    }
    else{
        word = reverse(tokens[i]);
        outString = build(outString, word);
        alternator = !alternator;
    }
}

//Show results
console.log(outString);

//Capitalize
function capitalize(inToken){
    return inToken.toUpperCase();
}

//Reverse
function reverse(inToken){
    var stringArray = inToken.split('');
    var reverseString = stringArray.reverse();
    return reverseString.join('');
}

//Build
function build(inString, inNewToken){
    return inString + ' ' + inNewToken;
}

- John March 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JavaScript:

var inString = "This is a test String!!";
var outString = "";

//Split
var tokens = inString.split(' ');

//Iterate
var alternator = false;
for(var i = 0; i < tokens.length; i++){

    var word;

    if(!alternator){
        word = capitalize(tokens[i]);
        outString = build(outString, word);
        alternator = !alternator;
    }
    else{
        word = reverse(tokens[i]);
        outString = build(outString, word);
        alternator = !alternator;
    }
}

//Show results
console.log(outString);

//Capitalize
function capitalize(inToken){
    return inToken.toUpperCase();
}

//Reverse
function reverse(inToken){
    var stringArray = inToken.split('');
    var reverseString = stringArray.reverse();
    return reverseString.join('');
}

//Build
function build(inString, inNewToken){
    return inString + ' ' + inNewToken;
}

- john March 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String str="this is a test string";
String arr[]=str.split(" ");
for (int i = 0; i < arr.length; i++) {
if (i%2==0) {
arr[i]=arr[i].replace(arr[i], arr[i].toUpperCase());
}else{
StringBuffer sb=new StringBuffer(arr[i]).reverse();
arr[i]=arr[i].replace(arr[i], sb);
}
}
System.out.println(Arrays.toString(arr));
}

- shoeb JD March 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringUpperReverse {

	public static String oddsUpperEvenReverse(String s){
		//put the words into an array using space as the delimiter and 
		//don't omit trailing spaces
		int size = s.split(" ", -1).length;
		String[] words = new String[size];
		words = s.split(" ", -1);
		
		//this will hold the number of the each word in the string 
		int wordCount=0;
		for(int i=0; i<size; i++){
		   //don't take spaces into account when counting the words
			//and if spaces are encountered do nothing
			if(words[i].equals(""))
				continue;
			else
				wordCount++;
			//convert the odd words to upper-case
			if((wordCount)%2!=0){
				words[i] = words[i].toUpperCase();
			}
			//and reverse the even
			else{
				words[i] = reverse(words[i]);
			}
		}
		StringBuilder sb = new StringBuilder("");
		//replace the spaces that were lost since they were used as delimiters 
		for(String word: words){
			sb.append(word + " ");
		}
		//remove the last space that was not there initially
		return sb.toString().substring(0,sb.toString().length()-1);
	}
	
	//helper method to reverse the even strings
	private static String reverse(String s)
	{
		if(s.length()==0)
		return s;
		else return s.charAt(s.length()-1) + reverse(s.substring(0,s.length()-1));
	}
	
	public static void main(String args[]){
		String s = " My  name    is Gabriel   and career  cup   challenges are awesome!   ";
		System.out.println(oddsUpperEvenReverse(s));
	}
}

- Gabriel G March 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java code to solve the problem:

public class StringUpperReverse {

	public static String oddsUpperEvenReverse(String s){
		//put the words into an array using space as the delimiter and 
		//don't omit trailing spaces
		String[] words = s.split(" ", -1);
		
		//this will hold the number of the each word in the string 
		int wordCount=0;
		for(int i=0; i<words.length; i++){
		   //don't take spaces into account when counting the words
			//and if spaces are encountered do nothing
			if(words[i].equals(""))
				continue;
			else
				wordCount++;
			//convert the odd words to upper-case
			if((wordCount)%2!=0){
				words[i] = words[i].toUpperCase();
			}
			//and reverse the even
			else{
				words[i] = reverse(words[i]);
			}
		}
		StringBuilder sb = new StringBuilder("");
		//replace the spaces that were lost since they were used as delimiters 
		for(String word: words){
			sb.append(word + " ");
		}
		//remove the last space that was not there initially
		return sb.toString().substring(0,sb.toString().length()-1);
	}
	
	//helper method to reverse the even strings
	private static String reverse(String s)
	{
		if(s.length()==0)
		return s;
		else return s.charAt(s.length()-1) + reverse(s.substring(0,s.length()-1));
	}
	
	public static void main(String args[]){
		String s = " My  name    is Gabriel   and career  cup   challenges are awesome!   ";
		System.out.println(oddsUpperEvenReverse(s));
	}
}

- gabriel.gab99 March 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void ModifyString(char* inputString);
void UpperWord(char* inputString, char* startChar, char* endChar);
void ReverseWord(char* inputString, char* startChar, char* endChar);

void ModifyString(char* inputString)
{
	char* startChar = inputString;
	char* endChar = startChar;

	bool isOddWord = true;
	
	// Walk the string
	while (1)
	{
		// If we found the end of a word
		if (*endChar == ' ' || *endChar == '\0')
		{
			// Make word upper case
			if (isOddWord)
				UpperWord(inputString, startChar, endChar);
			// Reverse string, not including the word ending character
			else
				ReverseWord(inputString, startChar, endChar - 1);

			isOddWord = !isOddWord;
			
			// Set our new start character, skipping over the ending character of space or null
			startChar = endChar + 1;
		}

		// If we hit the end of the string then exit
		if (*endChar == '\0')
			break;
		// Otherwise skip over our space character
		else
			endChar++;
	}
}

void UpperWord(char* inputString, char* startChar, char* endChar)
{
	// Convert the string not including the ending character (space or null)
	while (startChar != endChar)
	{
		// If this is a letter and it is lowercase
		if (*startChar >= 'a' && *startChar <= 'z')
		{
			*startChar = 'A' + (*startChar % 'a');
		}
		
		startChar++;
	}
}

void ReverseWord(char* inputString, char* startChar, char* endChar)
{
	while (startChar < endChar)
	{
		char swapChar = *endChar;
		*endChar = *startChar;
		*startChar = swapChar;

		startChar++;
		endChar--;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	char inputString[] = "This is a test String!!";

	ModifyString(inputString);
	cout << inputString << endl;
	return 0;
}

- CareerCupDom March 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

x = "hello"
y = x.upcase
puts y

-> HELLO

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

public String reverseEvenStringUppercaseOddString(String str) {
        int count = 0;
        int wordCount = 0;
        String revString = "";
        String output = "";
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) != ' ') {
                revString = str.charAt(i) + revString;
                count++;
            } else {
                if(count > 0) {
                    wordCount++;
                    if(wordCount % 2 == 0) {
                        output = output + revString;
                    } else {
                        output = output + str.substring(i - count, i).toUpperCase();
                    }
                } 
                revString = "";
                count = 0;
                output = output + str.charAt(i);
            }
        }
        if(count > 0) {
            wordCount++;
            if(wordCount % 2 == 0) {
                output = output + revString;
            } else {
                output = output + str.substring(str.length() - count, str.length()).toUpperCase();
            }
        }
        return output;

}

- Scorpion King April 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Below code is in C#
public static void ConvertOddWordsToUpperAndReverseEvenWords(string inputString)
        {
            int wordPosition = 1;
            string temp = string.Empty;
            char delimeter = ' ';
            StringBuilder sb = new StringBuilder();

            for (int counter = 0; counter <= inputString.Length - 1; counter++)
            {
                if (inputString[counter] != delimeter && counter != inputString.Length -1)
                {
                    temp += inputString[counter];
                }
                else
                {
                    if (wordPosition % 2 == 1)
                    {
                        sb.Append(temp.ToUpper()).Append(delimeter);
                    }
                    else
                    {
                        sb.Append(ReverseWord(temp)).Append(delimeter);
                    }
                    temp = string.Empty;
                    wordPosition++;
                }
            }

            Console.WriteLine("Input string: {0}", inputString);
            Console.WriteLine("Output String: {0}", sb.ToString());
            Console.ReadLine();
        }

private static string ReverseWord(string word)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = word.Length - 1; i >= 0; i--)
            {
                sb.Append(word[i]);
            }

            return sb.ToString();
        }

- Aarti April 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringAlgo {

private static String str = "This is test String";
private static String resultStr = "";

public static void main(String[] args) {
StringTokenizer strToken = new StringTokenizer(str);
int len = strToken.countTokens();
String arr[] = new String[len];
int i = 1,j=0;
while(strToken.hasMoreTokens())
{
if(i%2==1)
{
arr[j]= strToken.nextToken().toUpperCase();
}
else
{
String strEven = strToken.nextToken();
StringBuilder sb = new StringBuilder(strEven).reverse();
arr[j] = sb.toString();
}
i++;
j++;
}
for(int k = 0;k<arr.length;k++)
{
if(k==0)
{
resultStr = arr[k];
}
else{
resultStr = resultStr+" "+arr[k];
}
}
System.out.println("The final String is "+resultStr);
}
}

- Hari July 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

input_string = "This is a Test String input"


def reverse(words : []):
    if len(words) == 0:
        return ""
    else:
        first = words[0]
        words.pop(0)
        return first[::-1] + " " + toupper(words)


def toupper(words : []):
    if len(words) == 0:
        return ""
    else:
        first = words[0]
        words.pop(0)
        return first.upper() + " " + reverse(words)



words = input_string.split(" ")
print (toupper(words))

- Bucher September 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

input_string = "This is a Test String input"


def reverse(words : []):
    if len(words) == 0:
        return ""
    else:
        first = words[0]
        words.pop(0)
        return first[::-1] + " " + toupper(words)


def toupper(words : []):
    if len(words) == 0:
        return ""
    else:
        first = words[0]
        words.pop(0)
        return first.upper() + " " + reverse(words)



words = input_string.split(" ")
print (toupper(words))

- Bucher September 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String uppercaseAndReverseAlternately(String str) {
        if (str.length() == 0 || str == null) {
            return null;
        }

        String out = "";
        String temp = "";
        int count = 0;
        int i = 0;

        while (i < str.length()) {
            if (str.charAt(i) == ' ') {
                out = out + str.charAt(i);
                i++;
            } else {
                while (i < str.length() && str.charAt(i) != ' ') {
                    if (count % 2 == 0) {
                        temp = temp + (str.charAt(i) + "").toUpperCase();
                    } else {
                        temp = str.charAt(i) + temp;
                    }
                    i++;
                }
                out = out + temp;
                count++;
                temp = "";
            }
        }
        return out;
    }

- Scorpion King January 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Revers_String_Homework1 {

public static void main(String[] args) {

String str1 = "hi bob how are you";
String Rstr1 = Rstr(str1);
System.out.println(Rstr1);

}
private static String Rstr (String str1){
String reversStr = "";


String[] Arrey2 = str1.split("\\s+");

for( int i= 0; i<Arrey2.length; i++){
if( i %2 == 0 ){
Arrey2[i]= Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
}
reversStr= reversStr+" "+ Arrey2[i];
}
return reversStr;
}

}

- Maryna October 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

and

public class Ex_modify_TestString {
	public static void main(String[] args) {
		String str1 = "hi bob how are you";
		String Rstr1 = Rstr(str1);
		System.out.println(Rstr1);
	}

	private static String Rstr(String str1) {
		String reversStr = "";
		String[] Arrey2 = str1.split("\\s+");

		for (int i = 0; i < Arrey2.length; i++) {
			if (i % 2 == 0) {
				Arrey2[i] = Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
			}
			reversStr = reversStr + " " + Arrey2[i];
		}
		return reversStr;
	}
}

- Maryna October 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Ex_modify_TestString {
	public static void main(String[] args) {
		String str1 = "hi bob how are you";
		String Rstr1 = Rstr(str1);
		System.out.println(Rstr1);
	}

	private static String Rstr(String str1) {
		String reversStr = "";
		String[] Arrey2 = str1.split("\\s+");

		for (int i = 0; i < Arrey2.length; i++) {
			if (i % 2 == 0) {
				Arrey2[i] = Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
			}
			reversStr = reversStr + " " + Arrey2[i];
		}
		return reversStr;
	}
}

- marishkram October 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//C# code
                string[] input = "This is a test String!!".Split(' ');
                string inputword = string.Empty;
                string reverseword = string.Empty;
                string output = string.Empty;
                string word = string.Empty;
                for (int i = 0; i < input.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        output = output + " " + input[i].ToUpper();
                    }
                    else
                    {                        
                        word = input[i];
                        foreach (var item in word)
                        {
                            reverseword = item + "" + reverseword;
                        }
                        output = output + " " + reverseword;
                    }
                    reverseword = string.Empty;
                }
                Console.WriteLine(output.Trim());
                Console.ReadLine();

- Mallikarjun Birajdar November 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In python:

x=input("Please give an sentence:")
def format_word(statement):
    words_array=statement.split()
    output=[]
    for i in range(0,len(words_array)):
        if i % 2 ==0:
            output.append(words_array[i].upper())
        else:
            out=''
            in_value=words_array[i]
            for i in in_value:
                out=i+out
            output.append(out)
    return (' '.join(output))
format_word(x)

- jagannathans92 February 27, 2018 | 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