Microsoft Interview Question for Software Engineer in Tests


Team: MSIT
Country: United States




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

Why to use hashing when a simple look up table of size 256 is sufficient?
Then iterating through the string again and checking for the values should give you an answer
Eg:MICROSOFT
count['C']=1
count['F']=1
count['I']=1
count['M']=1
count['O']=2
count['R']=1
count['S']=1
count['T']=1

for(char ch : string.toCharArray())
{
if(count[ch] == 1)
return ch;
}

I can see one problem with this if the character set changes then we have to change the count array size. But we have to ask the interviewer for clarification.

- hello world March 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

i think using the array of size 256 will require an initial pass to initialize the array with 0 values, and this will take an additional o(n) steps which can be avoided if we used hashing, because i think a hashtable is initialized with 0 values automatically.

- hitman March 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

In programming languages like JAVA all arrays are initialized with default values, here the int array will contain zeros.

- Dev March 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@hello_world: which still takes time because it's still work that has to get done by the CPU.

- eugene.yarovoi March 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@eugene.yarovo
LOL! Then, hash table is initialized to zero by USB Controller? :D

- tera_baap March 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ tera_baap : epic :)

- aryan shah March 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@tera_baap: well no, of course not. I was just answering that one specific point someone else made, not addressing the whole discussion

- eugene.yarovoi November 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 4 vote

Crate the hashtable with string char as key and the increment the counter when you found the same char in the string , then iterate your hashtable whenever you first found the 1 counter that will be your first non-repeating char.

- Anonymous March 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think hash table iteration wont give you the "first" non-repeating char as the iterator is not expected to return the keys in order of insertion.

- jainbk March 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Easily fixed, though: Iterate over the characters in the string, in order, instead of iterating over the hash table.

- eugene.yarovoi March 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I don't think the first char with the counter 1 in the hash table is the first non-repeating char in the original string. You may forget the hashcode is generated.

- ascmomo March 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You can used LinkedHashMap instead of Hashtable which stores the keys on the order of insertion.So,all we need to do is to iterate through the keySet() who value is 1.

- sid_tintin May 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use set .. wont add duplicates first false operation of insertion is your non repeating character

- yogeshhan March 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

will not work, initially the set is empty, so every insertion will be a false opertion right?

- hello world March 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No, an insertion returns true if the insertion is successful (ie. the element is not already in the set), so the first time it returns false is when you hit the first duplicate.

This, however, doesn't tell you what the first non-repeating character is, only what the first repeating one is.

- Anonymous March 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int count[256];

for(i=0; i<strlen(input); i++) {
    count[input[i]] += 1;
}

for(i=0; i<strlen(input); i++) {
    if(count[input[i]] == 1)
        return input[i];
}

return "Non unique";

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

char str[] = "Hello WorldHe";
int i, j, l, cnt;
l=strlen(str);
for(i=0; i<l ; i++)
{
  cnt=0;
  for(j=i+1; j< ; j++)
  {
    if(str[j]==str[i])
      cnt++;
  }  
  if(!cnt)
  {
    printf("\n i: %d", i);
    break;
  }
}

- CheckThisResume.com March 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

use set operation, insert each char one by one from the end of the string, the last true operation is the first non repeating char

- luckycat March 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I do not think this approach will work try "abbcasjkk"

- Abhishek March 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

yeah, it does not work.

- Anonymous March 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

void main()
{
   
    int n, i=0 , j , count;
    char input[10] = "hhhello";
    char *ptr1;
    ptr1 = input;
    n = strlen(input);
   
    for(j=0;j<n;j++)    
    {
        i=0;
        count = 0;
        for(;i<n;i++)
        {
            
            if(ptr1[j] == input[i])
            {
                ++count;
             

            }
           
        }
       
        if (count == 1)
        {
            printf("The Answer is %c", ptr1[j]);
            break;
        }
    }
     
}

- Dhritiman Hazarika March 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static char getFirstNonReatingChar(String input){

boolean isFNR=false;
Set uniqueDs=new HashSet();


for(int i=0;i<input.length();i++){
char c=input.charAt(i);

isFNR=uniqueDs.add(c);
//This the duplicate
if(!isFNR){
i=-1;
uniqueDs=new HashSet();
input=input.replaceAll(c+"","");
}
}

return input.charAt(0);
}

- Abhishek March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

if you use only hash table or only counting array then you have to traverse the string twice making the complexity 2n. but if you use counting array along with a linked list then you can do it in one traversal and you can find kth non repeating character.

for example the input is "ccacbdedb". the steps of the algorithm are :
1. count of 'c' is 1 insert 'c' into the linked list and go ahead.
2. count of 'c' becomes 2 remove 'c' from the linked list and go ahead.
3. count of 'a' is 1 insert 'a' into the linked list and go ahead.
4. count of 'c' becomes 3 go ahead.
5. count of 'b' is 1 insert 'b' into the linked list and go ahead.
6. count of 'd' is 1 insert 'd' into the linked list and go ahead.
7. count of 'e' is 1 insert 'e' into the linked list and go ahead.
8. count of 'd' becomes 2 remove 'd' from the linked list and go ahead.
9. count of 'b' becomes 2 remove 'b' from the linked list and go ahead.

now the linked list contains only 'a' & 'e'. 'a' is the first non repeating character and 'e' is the second non repeating character. you can do it in O(n) (not O(2n)) time in single iteration.

- CAFEBABE March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

After hitting the repeated char, deleting the node is difficult handle. This logic wont for for the following example: abcdabcc with time complexity O(n). When you count for 'a' become 2, how do you know which node to be deleted with out traversing the node again?

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

public static int[] getlargest(int [] a, int k){
	int max = Integer.MIN_VALUE;
	int maxpos = 0;
	int [] arr = new int [k]; 
	for(int i=0; i<k; i++){
		for(int j=0; j<a.length; j++){
			if(a[j] > max){
				max = a[j];
				maxpos = j;
			}
		}
		arr[i] = max;
		a[maxpos] = Integer.MIN_VALUE;
		max = Integer.MIN_VALUE;
	}
	return arr;
}
	
public static void main(String [] args){
	int [] a = {3,5,6,41,4,7,1,2,8,19,65,21};
	int [] res = getlargest(a,4);
	for(int i=0; i<res.length; i++){
		System.out.println((i+1)+"th largest element is : "+res[i]);
	}
}

- CAFEBABE March 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This can also be done using a constant amount of memory in O(n) time

- Abdul Samad March 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This can also be done using a constant amount of memory in O(n) time

- Abdul Samad March 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char[] ch2 = "microsoft".toCharArray();

LinkedHashMap<Character, Integer> result1 = new LinkedHashMap<Character, Integer>();
for (int i = 0; i < ch2.length; i++) {
if (result1.containsKey(ch2[i]))
result1.put(ch2[i], -1);
else
result1.put(ch2[i], i);
}// cfimorst //ftsrcomi
for (char ch1 : result1.keySet())
if (result1.get(ch1) != -1) {
System.out.print(ch1);
break;
}

- Programmer March 20, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

question2:-solve same question by doing single pass.

- sk March 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static char findFirstNotRepeatChar(string inputStr)
{
char outChar = '\0';
int[] charList = new int[256];
for (int i = 0; i < inputStr.Length; i++)
{
charList[inputStr[i]]++;
}
for (int i = 0; i < inputStr.Length; i++)
{
if (charList[inputStr[i]] == 1)
{
outChar=inputStr[i];
break;
}
}
return outChar;
}

- JohnZhang March 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class FirstNonRepeatitiveCharacter {

	public static void main(String[] args) {

		String s = "alkdfskdjdff";
		@SuppressWarnings("unchecked")
		LinkedHashMap<String , String> map = (LinkedHashMap<String, String>) populateMap(s);
		Set<String> set = map.keySet();
		Iterator<String> itr = set.iterator();
		while(itr.hasNext()){
			String key = itr.next();
			if(map.get(key).equals(String.valueOf(1))){
				System.out.println(" The first non-repeatitive character is : " + key);
				return;
			}
		}
		
		

	}
	
	private static Map populateMap(String s){
		
		char[] a = s.toCharArray();
		LinkedHashMap<String, String> mMap = new LinkedHashMap<String, String>();

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

			String key = "" + a[i];
			int initalCount = 1;
			//Put of Map returns the previous value of the key.
			String value = mMap.put(key, String.valueOf(initalCount));
			
			//If the value == null, it means the key is being inserted for the first time
			// or the previous value of Key is null , which is not the case here
			
			//If the value != null, it means the key already exists.So,we should get the value
			// and increment it by 1
            
			if (value != null) {
				int currentCount = Integer.valueOf(value);
				currentCount += 1;
				mMap.put(key, String.valueOf(currentCount));
			}
		}
		return mMap;
	}

}

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

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class FirstNonRepeatitiveCharacter {

	public static void main(String[] args) {

		String s = "alkdfskdjdff";
		@SuppressWarnings("unchecked")
		LinkedHashMap<String , String> map = (LinkedHashMap<String, String>) populateMap(s);
		Set<String> set = map.keySet();
		Iterator<String> itr = set.iterator();
		while(itr.hasNext()){
			String key = itr.next();
			if(map.get(key).equals(String.valueOf(1))){
				System.out.println(" The first non-repeatitive character is : " + key);
				return;
			}
		}
		
		

	}
	
	private static Map populateMap(String s){
		
		char[] a = s.toCharArray();
		LinkedHashMap<String, String> mMap = new LinkedHashMap<String, String>();

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

			String key = "" + a[i];
			int initalCount = 1;
			//Put of Map returns the previous value of the key.
			String value = mMap.put(key, String.valueOf(initalCount));
			
			//If the value == null, it means the key is being inserted for the first time
			// or the previous value of Key is null , which is not the case here
			
			//If the value != null, it means the key already exists.So,we should get the value
			// and increment it by 1
            
			if (value != null) {
				int currentCount = Integer.valueOf(value);
				currentCount += 1;
				mMap.put(key, String.valueOf(currentCount));
			}
		}
		return mMap;
	}

}

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

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class FirstNonRepeatitiveCharacter {

	public static void main(String[] args) {

		String s = "alkdfskdjdff";
		@SuppressWarnings("unchecked")
		LinkedHashMap<String , String> map = (LinkedHashMap<String, String>) populateMap(s);
		Set<String> set = map.keySet();
		Iterator<String> itr = set.iterator();
		while(itr.hasNext()){
			String key = itr.next();
			if(map.get(key).equals(String.valueOf(1))){
				System.out.println(" The first non-repeatitive character is : " + key);
				return;
			}
		}
		
		

	}
	
	private static Map populateMap(String s){
		
		char[] a = s.toCharArray();
		LinkedHashMap<String, String> mMap = new LinkedHashMap<String, String>();

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

			String key = "" + a[i];
			int initalCount = 1;
			//Put of Map returns the previous value of the key.
			String value = mMap.put(key, String.valueOf(initalCount));
			
			//If the value == null, it means the key is being inserted for the first time
			// or the previous value of Key is null , which is not the case here
			
			//If the value != null, it means the key already exists.So,we should get the value
			// and increment it by 1
            
			if (value != null) {
				int currentCount = Integer.valueOf(value);
				currentCount += 1;
				mMap.put(key, String.valueOf(currentCount));
			}
		}
		return mMap;
	}

}

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

//ch[] is given character array
n=strlen(ch); 
for(i=0;i<n;i++)
{
  int j=i;

  while(ch[i]==ch[i+1] && i<n-1)i++;
  if(j==i)
  {
  printf("%c",ch[i]);
  break;
  }
}

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

question was using only 1 bit of extra space

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

Print all the elements of the ArrayList consisting an ArrayList using C# ?

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

First iteration ==> O(n)
Add the characters into a HashMap with String as key and the value as integer count.

Second iteration ==> O(n)
Create a queue, FirstInFirstOut
Traverse on string{
Check if the String key in hashMap is 1
then insert into Queue
}

At the end, You will get the first non repeating, second non repeating ... in order from the queue. (On dequeue method)

- Vamsi February 10, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thus making the complexity O(n).

But has two Data Structures used

- savk.mn February 10, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

package nonRepeating;

import java.util.Scanner;

public class nonRepeating {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter the string:");
		String s=scan.nextLine();
		int len=s.length();
		int j=0,count=0;
	
		
		for(int i=0;i<s.length();i++){
			char c=s.charAt(i);
			count=0;
	        while(j<len){
	        	if(c==s.charAt(j)){
	        		count++;}
	          	j++;
	        }
	        if(count==1){
	        	System.out.println(s.charAt(i));
	        	break;
	        }
	        
			}
			
			
		}
		
		
		
	}

- div April 04, 2017 | 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