Microsoft Interview Question for Software Engineer in Tests


Team: Server and tools in microsoft erp
Country: United States
Interview Type: In-Person




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

#include<iostream>
#include<string>

using namespace std;

void reverse(string& str, int st, int end) {
if (st > end) return;

char c;
int i,j;
for (i=st, j=0; i<(st+end)/2; ++i, ++j) {
c = str[i];
str[i] = str[end-j];
str[end-j] = c;
}
return;
}

int main() {
string str = "hello world";
cout << "before : " << str << endl;
int p = str.find(' ');
int len = str.length();
reverse(str, 0, p-1);
reverse(str, p+1, len-1);
cout << "after : " << str << endl;
}

- anjalpetty April 20, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

who said that there is only one space in the string??

- Pawan May 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

who said that there is only one space in the string??

- Pawan May 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

who said that there is only one space in the string??

- Pawan May 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if there is more than 2 word with having different no of words??

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

void subreverse(char *str, int begin, int end)
{
end--;

while ( begin < end )
{
swap(str[begin++], str[end--]);
}
}
char* reversestr(char *str)
{
int len = strlen(str);

int begin = 0;
int end = 0;

for ( int i=0; i<len; )
{
while( i!=0 && str[i] != '\0' && str[i] != ' ')
i++;

if ( str[i] == '\0' )
break;
else if ( i== 0)
begin = i;
else
begin = i+1;

i++;

while ( str[i] != '\0' && str[i] != ' ')
i++;

end = i;

subreverse(str, begin, end);
}

return str;
}

- Ethan April 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class test {
private void reverseWords(StringBuffer sentence, int length) {
for(int j=0, i=0; i < length ; i++) {
if(sentence.charAt(i) == ' ' || i + 1 == length) {
if(i + 1 == length) {
sentence = reverseWord(sentence,j,i);
} else {
sentence = reverseWord(sentence,j,i-1);
}
j = i + 1;
}
}
System.out.println(sentence);
}
private StringBuffer reverseWord(StringBuffer sentence, int start, int end) {
while(start < end) {
char temp = sentence.charAt(start);
sentence.setCharAt(start, sentence.charAt(end));
sentence.setCharAt(end, temp);
start++;
end--;
}
return sentence;
}
public static void main(String args[]) {
test t = new test();
StringBuffer sb = new StringBuffer("hello world");
t.reverseWords(sb, sb.length());
}
}

- Srivignesh M April 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverseWords(char *s)
{
char *begin = s;
char *temp = s;
while( *temp )
{
temp++;
if (*temp == '\0')
{
reverse(begin, temp-1);
}
else if(*temp == ' ')
{
reverse(begin, temp-1);
begin = temp+1;
}
}
}

- Sidhartha April 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* Author - JITENDRA SINGH
CDAC HYDERABAD
*/
void rev(char *l,char *r)
{
int i=0,t;
while(l<r)
{
t = *l;
*l = *r;
*r = t;
l++;
r--;
}
}

void main()
{
char *x,*y,*S1,str[150];
printf("\n Enter String\n");
fgets(1,str ,150);
printf("\ngiven = %s",str);
for(S1 =str ; *S1 ;S1++);

x = str;
y = str;

while(x++ < S1)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}

printf("\n\nconverted=%s",str);

}

- JITENDRA SINGH April 25, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Better solution:-
1) Split the string taking "space" as delimiter.
2)now just reverse the array of String array using reverse() of StringBuffer.

- aditya May 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Better solution:-
1) Split the string taking "space" as delimiter.
2)now just reverse the array of String using reverse() of StringBuffer.

- aditya May 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Better solution:-
1) Split the string taking "space" as delimiter.
2)now just reverse the array of String using reverse() of StringBuffer.

- aditya May 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think your solution is the right one, but the interviewer will surely ask you to implement the split function :D

- too easy May 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int i, j;
string str = "hello world";
string target = "";

string[] spilted = str.Split(' ');

for (i = 0; i < spilted.Length; i++)
{
char[] chars = spilted[i].ToCharArray();
for (j = (chars.Length-1); j >= 0; j--)
target = target + chars[j].ToString();

target = target + " ";
}

- Jatin Kacha May 15, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

// this program reverse string as follows : hello string --> olleh gnirts
void reverse(char[], int, int);
int main()
{
int l;
printf("enter the length of string\n");
scanf("%d", &l) ;
getchar();
char *str = malloc(sizeof(char) * l);
printf("enter the string\n");
gets( str);
int first = 0,i,last;
int len = strlen(str);

for(i=0; i<len; i++)
{
if(str[i] == ' ')
{
last = i-1;
reverse(str,first,last);
first = i+1;
}
if(i == len-1)
{
last = len-1;
reverse(str,first,last);
}
}
printf("%s\n", str);
}

void reverse(char str[], int first, int last)
{
int i,j;
char temp;
for(i=first,j=last; i<j; i++,j--)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
}

}
// its complexity is O(n*n) ..can anybody suggest some better algorithm?

- Pawan Sharma May 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

typedef struct _node
{
    char c;
    struct _node *next;
}node;

main()
{
char    *string = "Hello World This is a Sample Program";
    node    *word = NULL;

    while(*string)
    {
        if(*string != ' ')
        {
            word = push(word, *string);
            string++;
            continue;
        }
        print(word);
        printf(" ");
        freenode(word);
        word = NULL;
        string++;
    }
    printf(" ");
    print(word);
}

node* push(node *prev, char chr)
{
    node *link = NULL;
    link = (node *) malloc(sizeof(node));
    link->c = chr;
    link->next = prev;
    return link;
}

void print(node *word)
{
    if(word == NULL)
        return;
    printf("%c", word->c);
    print(word->next);
}

void freenode(node *fnode)
{
    if(fnode->next != NULL)
        freenode(fnode->next);
    free(fnode);
}

- Ravindian May 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverseWordByWord(char c[])
{
	int l = strlen(c);
	char *temp = &c[0];
	char *start_pos = NULL;
	stack<char> s;
	while (*temp != '\0')
	{
		if (*temp != ' ') {
			if (start_pos == NULL) {
				start_pos = temp;
			}
			s.push(*temp);
		} else {
			while (s.size() > 0) {
				*start_pos = s.top();
				s.pop();
				start_pos++;
			}
			start_pos = NULL;
		}
		temp++;
	}
	if (s.size() > 0) {
		while (s.size() > 0) {
			*start_pos = s.top();
			s.pop();
			start_pos++;
		}
	}
}

- Anonymous May 28, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>

int main()
{

char a[]="i am good";
char *p,*q,*r;
int c=0;

p=a;

while(*p!='\0')
{
p++;
}
p--;



while(c<strlen(a))
{


*q =*p;

q++;

p--;
c++;
}
c=0;
*q='\0';
while(c<strlen(a))
{

q--;
c++;
}


printf("%s",q);
getchar();
}
The above is the code for reversing the string or even a sentence which is a collection of words. Now if we want the words in the string to be reversed take an array of pointer like
char *a[]="i am solid";
now a[0] contains address of 'i" a[1] contains address of "am" a[2] contains address of "solid" now pass each and every value of a ie; a[0] a[1] a[2] to the above program assuming the above program as a function. Now your char *a[] contains "I ma dilos"

- phani krishna Amazon May 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

i have a simple solution to this problem.
we will traverse the string and push the charachters in a stack, until we get a space.
when space is encountered, empty the stack in a queue, and continue traversing the string.
finally the answer will be available in the queue.
Stack will reverse the individual words while queue will maintain there order.

please reply if you have any say on this.
Thanks
Ankit

- Anonymous May 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

What if we use stack to reverse a string.
1. Push all the characters in to stack.
2. Pop them and add it to StringBuffer.

- pavan.akella1 May 31, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

we can use that method when we dnt have access to rev funct.

- Anonymous May 31, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void ReverseWordOfString(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                Console.WriteLine("String is empty");
                return;
            }

            Stack<char> charStack = new Stack<char>();
            var charArray = s.ToCharArray();
            int length = charArray.Length;
            Queue<char> result = new Queue<char>();
            Console.WriteLine("input string : {0}", s);
            for (int i = 0; i < length; i++)
            {
                if (charArray[i] != ' ')
                {
                    charStack.Push(charArray[i]);
                }
                else
                {
                    while (charStack.Count > 0)
                    {
                        result.Enqueue(charStack.Pop());
                    }
                    result.Enqueue(' ');
                }
            }
            while (charStack.Count > 0)
            {
                result.Enqueue(charStack.Pop());

            }

            Console.Write("String After reversing the words : "); Console.Write(result.ToArray());
            Console.WriteLine();

        }

- ajaypathak July 25, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Can you provide more test cases over it ? Why do we need to use a Stack in this case ?

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

Following function can be used

void reverseWordByWord(char string[]) {

	int len = strlen(string);
	char *start = &string[0];
	char *end = NULL;
	for (int i=0;i<len;++i) {
		if (string[i] == ' ') {
			end = &string[i-1];
			reverse(start, end);
			start = i+1<len?&string[i+1]:NULL;
		}
	}
        //reverse the last word
	end = &string[len-1];
	reverse(start, end);
}

- crystal.rishi2 October 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

RegEx can be used to split words.

public static string ReverseWordsInAString(string inputString)
        {            
            StringBuilder sb = new StringBuilder();
            //split the word with Regx                      
            Regex regex = new Regex(@"\b+\w+|[\s.',:?]*\b");
            MatchCollection matches = regex.Matches(inputString);
            
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    sb.Append(RevereseString(m.Value));
                }                
            }
            return sb.ToString();        
        }


        private static string RevereseString(string s)
        {
            //Check for Null/Empty string
            if (!string.IsNullOrWhiteSpace(s))
            {
                char[] newS = s.ToCharArray();
                Array.Reverse(newS);
                return new string(newS);
            }
            return s;
        
        }

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

c++ code

#include<iostream>
#include<string>
using namespace std;
void ReverseLetters(std::string& s)
{
    int i = 0;
    int start = 0;
    int l = s.length();
    while (i < l)
    {
        if (s[i+1] == ' ')
        {
            int end = i;
            while(start < end){
                char c = s[start];
                s[start++] = s[end];
                s[end--] = c;            }
            i++;
            while(s[i] == ' ' and i < l)
            {
                i++;
            }
            start = i;
        }
        i++;
    }
}

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

private String ReverseWords(String s, String separators = " /t.,?!")
        {
            // ensure that the string has enough characters to reverse
            if (s.Length <= 1) { return s; }

            // check each character
            StringBuilder ret = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                if (separators.Contains(s[i]))
                {
                    ret.Append(s[i]);
                    continue;
                }

                // search for the rest of the word
                Stack<char> wordReverser = new Stack<char>();
                while (i < s.Length)
                {
                    if (separators.Contains(s[i]))
                    {
                        i--;  // backup i to be correct in the "for" loop
                        break;
                    }
                    wordReverser.Push(s[i]);
                    i++;
                }

                // empty word in reverse
                while (wordReverser.Count > 0)
                {
                    ret.Append(wordReverser.Pop());
                }
            }

            return ret.ToString();
        }

- C# for word reverse in a sentence, accounting for multiple separators June 05, 2014 | 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