Microsoft Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
2
of 6 vote

public static void reverseString(String str){
        int len = str.length();
        char arr[] = str.toCharArray();
        for(int i=0, j = len-1; i<=j; i++,j--){
            if(arr[i] == ' ') i++;
            if(arr[j] == ' ') j--;

            char tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;

        }
        System.out.println(arr);

- Dinesh Kumar July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

java Test ' abbbb cd ee '
' abbbb cd ee '
' eedc bb bba '
====================
java Test 'q abbbb xc cd ee q'
'q abbbb xc cd ee q'
'q eedc cx bb bba q'

==========
Summary, there is some flaw.

- Anon July 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

dinesh kumar's solution doesn't handle multiple spaces well.

- DarkKnight August 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If the in put contains more than 1 consecutive spaces then there a flaw, please handle, i.e. skip i & j until next char is not white space

- Vinayak S M September 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just put the swap inside else block to handle multiple consecutive spaces if any.

the rest looks good.

- Solomon November 08, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringSvc
{
	public String reverse(String s)
	{
		if(s==null)
		{
			throw new NullPointerException("input string cannot be null");
		}
		StringBuilder sb=new StringBuilder();
		
		
		int i=0;
		int j=a.length()-1;
		
		while(i<a.length() && j>=0)
		{
			if(s.charAt(i)==' ')
			{
				sb.append(' ');
			}else{
				while(s.charAt(j)==' ')
				{
					j--;
				}
				sb.append(s.charAt(j--));
				
			}
			i++;
		}
		return sb.toString();
		}
		
	}
	
	public static void main(String[] args)
	{
		String s= " a b "//should return " b a "
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		s=" a"//should return " a"
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		s= " ab c"//should return (" cb a")
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		
	}
}

- divm01986 July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

//Ignore previous solution, I misread the question.

public class StringSvc
{
	public String reverse(String s)
	{
		if(s==null)
		{
			throw new NullPointerException("input string cannot be null");
		}
		StringBuilder sb=new StringBuilder();
		
		
		int i=0;
		int j=a.length()-1;
		
		while(i<a.length() && j>=0)
		{
			if(s.charAt(i)==' ')
			{
				sb.append(' ');
			}else{
				while(s.charAt(j)==' ')
				{
					j--;
				}
				sb.append(s.charAt(j--));
				
			}
			i++;
		}
		return sb.toString();
		}
		
	}
	
	public static void main(String[] args)
	{
		String s= " a b "//should return " b a "
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		s=" a"//should return " a"
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		s= " ab c"//should return (" cb a")
		System.out.println("start: " + s);
		s=StringSvc.reverse("result: " + s);
		
	}
}

- divm01986 July 22, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

divm01986, string builders shouldn't be used for adding single characters. it is causing too much overhead.

- DarkKnight August 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseString(String str)
	{
		char[] arr = str.toCharArray();
		char temp;
		int i = 0;
		int j = str.length() - 1;
		while(i < j)
		{
			while(Character.isWhitespace(arr[i]))
				i++;
			while(Character.isWhitespace(arr[j]))
				j--;
			temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
			i++;
			j--;
		}
		return new String(arr);
	}

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

public static String reverseString(String str)
	{
		char[] arr = str.toCharArray();
		char temp;
		int i = 0;
		int j = str.length() - 1;
		while(i < j)
		{
			while(Character.isWhitespace(arr[i]))
				i++;
			while(Character.isWhitespace(arr[j]))
				j--;
			temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
			i++;
			j--;
		}
		return new String(arr);
	}

- Atom July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

why stop when i>=j ? we need to reverse the entire string.

- DarkKnight August 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseString(String str)
	{
		char[] arr = str.toCharArray();
		char temp;
		int i = 0;
		int j = str.length() - 1;
		while(i < j)
		{
			while(Character.isWhitespace(arr[i]))
				i++;
			while(Character.isWhitespace(arr[j]))
				j--;
			temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
			i++;
			j--;
		}
		return new String(arr);
	}

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

public static String reverseNoSpace(String inputString) {
        if(inputString == null) throw new NullPointerException("Input can not be null");
        if(inputString.length() == 0) return inputString;
        char[] chars = inputString.toCharArray();
        StringBuilder sb = new StringBuilder();
        int j = 0, i = chars.length - 1;
        char temp;
        while(i > j) {
            if(chars[i] == ' '){
                i--;
                continue;
            }
            if(chars[j] == ' '){
                j++;
                continue;
            }
            temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i--;
            j++;
        }
        return sb.append(chars).toString();
    }

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

public static String reverseNoSpace(String inputString) {
        if(inputString == null) throw new NullPointerException("Input can not be null");
        if(inputString.length() == 0) return inputString;
        char[] chars = inputString.toCharArray();
        StringBuilder sb = new StringBuilder();
        int j = 0, i = chars.length - 1;
        char temp;
        while(i > j) {
            if(chars[i] == ' '){
                i--;
                continue;
            }
            if(chars[j] == ' '){
                j++;
                continue;
            }
            temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i--;
            j++;
        }
        return sb.append(chars).toString();
    }

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

public static String reverseNoSpace(String inputString) {
        if(inputString == null) throw new NullPointerException("Input can not be null");
        if(inputString.length() == 0) return inputString;
        char[] chars = inputString.toCharArray();
        StringBuilder sb = new StringBuilder();
        int j = 0, i = chars.length - 1;
        char temp;
        while(i > j) {
            if(chars[i] == ' '){
                i--;
                continue;
            }
            if(chars[j] == ' '){
                j++;
                continue;
            }
            temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i--;
            j++;
        }
        return sb.append(chars).toString();

}}

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

void function(string& str)
{
    int len = str.length();
    int left = 0, right = len-1;
    while(left<=right)
    {
        while(str[left] == ' ')
            left++;
        while(str[right] == ' ')
            right--;
        swap(str[left], str[right]);
        left++;
        right--;
    }
}

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

def reverse(s):
    l = list(s)
    l2 = [c for c in l if c != ' ']
    j = 0

    for i in range(len(l) - 1, -1, -1):
        if l[i] == ' ':
            continue
        else:
            l[i] = l2[j]
            j += 1

    return ''.join(l)

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

void reverseStrExctSpace(char cArr[N])
{
	char temp;
	for(int i=0,j=N-1;i<=N/2,j>=N/2;i++,j--)
	{
		if(cArr[i]!=' ' && cArr[j]!=' ')
		{
			temp = cArr[i];
			cArr[i] = cArr[j];
			cArr[j] = temp;
		}
	}
}

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

Java Code:

public static String reverse(String string){
		char[] charArray = string.toCharArray();
		for(int start=0,end=charArray.length-1; start<end; start++,end--){
			while(start<charArray.length && charArray[start]==' '){
				start++;
			}
			
			while(end>-1 && charArray[end]==' '){
				end--;
			}
			
			if(start<end){
				char temp = charArray[start];
				charArray[start] = charArray[end];
				charArray[end] = temp;
			}
		}
		return new String(charArray);
	}

- Sharif Rahaman July 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseString {

	public static void main(String[] args) {
		StringBuffer str = new StringBuffer();
		StringBuffer strReverse = new StringBuffer();
		str = str.append("This is a red flower");
		String[] strArray = str.toString().split("\\s");
		for (int i=0;i<strArray.length;i++){
			StringBuffer strStore = new StringBuffer();
			strStore.append(strArray[i]);
			strStore.reverse();
			strArray[i] = strStore.toString();
			strReverse.append(strArray[i]);
			strReverse.append(" ");
			
		}
		System.out.println(strReverse);
	}

}

- sharma.sucheta July 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

this one whill work

public static String reversed2(String test)
	{
		char[] revers= new char[100]; int j=0;
		char[] revers2 = new char[100];
		for(int i =(test.length()-1);i>=0;i--)
		{
			if(test.charAt(i) != ' ')
			revers[j++] = test.charAt(i);	
		}
		System.out.println(new String(revers));
		j=0;
		int k =0;
		for(int i =0;i<test.length();i++)
		{
			if(test.charAt(i)==' ')
			{
				revers2[j++]=test.charAt(i);
			}
			else
			{
			revers2[j++]= revers[k++];
			}
		}
			return  new String(revers2);
	}

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

With Python:

""" Reverse string except spaces. A string has mix of alphabets and spaces.
    Your task is to reverse the string, but preserve the positions of spaces.
    For example, reverse of " a if" is " f ia"."""

def reverse_string(input_str):
    return input_str[::-1]

def reverse_string_space_check(input_str):
    out_str,low_index = "",0
    for id,ch in enumerate(input_str):
        if ch == " ":
            if low_index == id:
                # This check will reduce the number of calls of reverse_string function
                # code will work fine even without the if check and just keeping whatever
                # in else part
                out_str = out_str + " "
            else:    
                out_str = out_str + reverse_string(input_str[low_index:id]) + " "
            low_index = id+1
    else:
        out_str = out_str + reverse_string(input_str[low_index:])+" "
    return out_str

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

With Python:

def reverse_string(input_str):
    return input_str[::-1]

def reverse_string_space_check(input_str):
    out_str,low_index = "",0
    for id,ch in enumerate(input_str):
        if ch == " ":
            if low_index == id:
                # This check will reduce the number of calls of reverse_string function
                # code will work fine even without the if check and just keeping whatever
                # in else part
                out_str = out_str + " "
            else:    
                out_str = out_str + reverse_string(input_str[low_index:id]) + " "
            low_index = id+1
    else:
        out_str = out_str + reverse_string(input_str[low_index:])+" "
    return out_str

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

#include<iostream>
#include<string>
using namespace std;
void ReverseStringWithoutSpaces(string org)
{
	char temp;
	int len = org.length();

	for(int i=0, j=len-1; i<=j;)
	{
		//cout << "\n INFO: Iteration " << org[i] << " Compare with " << org[j];
		if(org[i] != ' ' && org[j] != ' ')
		{
			temp = org[i];
			org[i] = org[j];
			org[j] = temp;
			i++;
			j--;
		}
		else
		{
			if(org[i] == ' ')
			{
				i++;
			}
			if(org[j] == ' ')
			{
				j--;
			}
		}

	}

	

	cout << "\n";
	cout << "INFO:"<< org; 
}
int main()
{
	string s= "";
	cout << "\n Enter a string for reversal ";
	getline(cin, s);
	ReverseStringWithoutSpaces(s);
	return 0;
}

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

#include<iostream>
#include<string>
using namespace std;
void ReverseStringWithoutSpaces(string org)
{
char temp;
int len = org.length();

for(int i=0, j=len-1; i<=j;)
{
//cout << "\n INFO: Iteration " << org[i] << " Compare with " << org[j];
if(org[i] != ' ' && org[j] != ' ')
{
temp = org[i];
org[i] = org[j];
org[j] = temp;
i++;
j--;
}
else
{
if(org[i] == ' ')
{
i++;
}
if(org[j] == ' ')
{
j--;
}
}

}



cout << "\n";
cout << "INFO:"<< org;
}
int main()
{
string s= "";
cout << "\n Enter a string for reversal ";
getline(cin, s);
ReverseStringWithoutSpaces(s);
return 0;
}

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

public static String reverseString(String str)
	{
		System.out.println(str);
		String reversedString = "";
		char arr[] = str.toCharArray();
		int length =  arr.length;
		int j = length-1;
		
		for(int i=0; i<length; i++){
			if(arr[i] == ' '){
				System.out.print(" ");
			}else{
				if(j>=0)
				{
					while(arr[j] == ' '){
						j--;
					}
					System.out.print(arr[j]);
					j--;
				}
			}
		}		
		return reversedString;
	}

- Neth July 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Didn't really need to return a string. I forgot to make it void and comment
the return value...

- nxp2910 July 27, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's a Java function:

public static String reverseString(String str)
	{
		System.out.println(str);
		String reversedString = "";
		char arr[] = str.toCharArray();
		int length =  arr.length;
		int j = length-1;
		
		for(int i=0; i<length; i++){
			if(arr[i] == ' '){
				System.out.print(" ");
			}else{
				if(j>=0)
				{
					while(arr[j] == ' '){
						j--;
					}
					System.out.print(arr[j]);
					j--;
				}
			}
		}		
		return reversedString;
	}

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

Here's a Java code

public static String reverseString(String str)
{
System.out.println(str);
String reversedString = "";
char arr[] = str.toCharArray();
int length = arr.length;
int j = length-1;

for(int i=0; i<length; i++){
if(arr[i] == ' '){
System.out.print(" ");
}else{
if(j>=0)
{
while(arr[j] == ' '){
j--;
}
System.out.print(arr[j]);
j--;
}
}
}
return reversedString;
}

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

Hi,
It can be easily solved using following code:

--->i=0,m=0;
--->end=length(source)
--->while(i<length(source))
		lengthWord=0
		while(source[i]!=' ')
			lengthWord++
			i++
		for(j=0;j<lengthWord;j++)
			target[m]=source[end]
			m++
			end--
		target[end--]=' '
		i++

- soni.komal712 July 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseString(String str)
{
char[] arr = str.toCharArray();
char temp;
int i = 0;
int j = str.length() - 1;
while(i < j)
{
while(Character.isWhitespace(arr[i]))
i++;
while(Character.isWhitespace(arr[j]))
j--;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
return new String(arr);
}

- Guanghui Zhang September 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseString(String str)
{
char[] arr = str.toCharArray();
char temp;
int i = 0;
int j = str.length() - 1;
while(i < j)
{
while(Character.isWhitespace(arr[i]))
i++;
while(Character.isWhitespace(arr[j]))
j--;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
return new String(arr);
}

- Guanghui Zhang September 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseString {
	
	public static void main(String[] args) {
		String input = " the quick brown fox jumps over the lazy dog";
		char[] c = input.toCharArray();
		int i = 0;
		int j = c.length - 1;
		while (i <= j) {
			while (c[i] == ' ') {
				i++;
			}
			while (c[j] == ' ') {
				j--;
			}
			char k = c[i];
			c[i] = c[j];
			c[j] = k;
			i++;
			j--;
		}
		
		System.out.println(new String(c));
	}
	
}

- madi.sagimbekov October 14, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var array = input.ToArray();
int left = 0, right = array.Length - 1;
while(left < right)
{
	while (left < right && array[left] == ' ') left++;
	while (left < right && array[right] == ' ') right--;

	char swap = array[left];
	array[left] = array[right];
	array[right] = swap;

	left++;
	right--;
}

- renbin October 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In C/C++, the solution code for this could be as follows:

include<string.h>

char* reverseSpecial(char* str){
	int len = strlen(str);
	char* res = (char*) malloc(sizeof(char)*len);
	strcpy(res, str);
	char* left = res;
	char* right = res + ( len - 1 );

	while (left <= right){
		Boolean hadSpace = false;
		if (*left == ' '){
			left++;
			hadSpace = true;
		}
		if (*right == ' '){
			right++;
			hadSpace = true;
		}
		if (hadSpace)
			continue;
		char temp = *left;
		*left = *right;
		*right = temp;
		left++;
		right--;
	}
	return res;
}

The complexity of this algorithm would be O(n/2) = O(n).

- Alder Matus October 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C:

#include "stdio.h"
#include "string.h"
char * reverse(char *str) {
	int i=0, j=strlen(str)-1;
	char tmp;

	while(i < j) {
		while(str[i] == '  ') i++;
		while((str[j] == '  ') && (i < j)) j--;

		if((str[i] != '\0') && (i < j)) {
			// swap
			tmp = str[i];
			str[i] = str[j];
			str[j] = tmp;
			i++; j--;
		}
	}
}

- Silenka April 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse(s):
ret = list(s)
i = 0
j = len(ret)-1

while i<j:
if ret[i] != ' ' and ret[j] != ' ':
tmp = ret[i]
ret[i] = ret[j]
ret[j] = tmp
i += 1
j -= 1
elif ret[i] == ' ':
i += 1
elif ret[j] == ' ':
j -= 1

return ''.join(ret)

- Praveen April 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote
Here's the php solution: {{{ $string = "co oool ex mple"; $j = count($string) - 1; for ($i = 0; $i < (count($string)/2); $i++, $j--) { if !($string[$i] == ' ' || $string[$j] ==' ') swap($string[$i], $string[$j]); } function swap(&$x,&$y) { $tmp=$x; $x=$y; $y=$tmp; } - hayder.net July 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Here's the php solution:

$string = "co oool ex mple"; 

$j = count($string) - 1; 
for ($i = 0; $i < (count($string)/2); $i++, $j--) { 
    if !($string[$i] == ' ' || $string[$j] ==' ') 
    swap($string[$i], $string[$j]); 
} 
function swap(&$x,&$y) { 
    $tmp=$x; $x=$y; $y=$tmp; 
}

- hayder.net July 22, 2015 | Flag


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