Microsoft Interview Question for Interns


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
7
of 9 vote

This can be resolved using a simple approach - no hashmaps. You can reduce your complexity to O(N) by simply using an array of size 128 characters (to represent ASCII values). This boolean array will track the characters you encounter as you iterate through the string.

Implementation below:

String removeDuplicates(String str) {
	StringBuilder sb = new StringBuilder();
	boolean[] char_set = new boolean[128];
		
	for (int i = 0; i < str.length(); i++) {
		int c = str.charAt(i);
		if (!char_set[c]) {
			sb.append((char)c);
			char_set[c] = true;
		}
	}
	return sb.toString();
}

- vincethecoder December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

"in place"?

- guest December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

String is an immutable object. "in place" modification is not possible!

- vincethecoder December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ guest this is 'in place'. why do you think its otherwise?

- Anonymous December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I agree with your algorithm.

- DoZerg December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I just read the definition of inplace. I always thought that no extra memory (except for small variables) can be used!
This seems valid except that in an inplace algorithm, input is replaced by output (ref Wikipedia). You are using O(n) memory for output. The original string needs to be modified into output.
Thanks anyways! :)

- alex December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

No extra memory is being used here, whatever String is being passed in, a boolean array of 128 length is being created therefore space is not dependent on the input in this case, therefore Space = O(1).
O(1) space does not always mean using a single variable, it can be a constant sized array like in this proposed solution. I'm 99.99% sure if you gave this solution to your interviewer, he would have been satisfied.

- Anonymous December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If we are just talking about English characters, then a single integer variable can serve as our hashmap; with A to Z mapped to bits 0 to 25 within the integer.

- IntwPrep.MS December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@IntwPrep.MS usually strings can be composed of ASCII or Unicode values for instance. During an interview, it is ideal to clarify the kind of strings we are dealing with and probably proceed to determine whether we would use 128 or 256 characters.

- vincethecoder December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Strings are not immutable in C

- nf April 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Hey guys, I think it would be simplest just to use a HASHSET.
With the if statement we try to add the current character to the hash set; if we succeed, it means that the char is encountered for the first time, so we increment the counter i, otherwise (when if returns false), we just remove the particular char. Note that the value of i is not incremented.

Hope it helps. :)

public static String cocoBee(String str){
		
		StringBuilder sb = new StringBuilder(str);
		HashSet<Character> hs = new HashSet<>();
		
		for(int i = 0; i < sb.length(); ){
			
			
			if(hs.add(sb.charAt(i))){
				i++;
			}
			else{
				sb.deleteCharAt(i);
			}
			
		}
		return sb.toString();
	}

public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner scanner = new Scanner(System.in);
		String str = scanner.next();
		String str2 = cocoBee(str);
		
		System.out.println(str2);

	}

- cocoBee December 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think the question is about removing duplicate characters from the string. For example: If the string is "amazon", the output should be "amzon".
This can be done in O(N) using a HashMap.
Algorithm:
1. Traverse the string character by character
2. Enter the character in the HashMap<Character, Boolean> as key if it is not already present
3. If a character is already in HashMap, we found a duplicate.
4. Based on the requirement, we can either just display the characters and skip the duplicate characters OR store the characters in a character array and return the resultant array as a String.

- Exception December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Please do read the question again. The solution you mentioned isn't inplace.

- alex December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

OP, you asked for O(n) solution and he gave you O(n) solution. I'm sure the interviewer wasn't satisfied because you gave him O(nlog(n)) at best.

- Anonymous December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ANon:

In-place is the keyword here. I hope you understand the meaning of that...

- Anonymous December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

@Alex
In-place means constant space, independent on the input size. In this case the hashmap can be a single integer irrespective of the input string length. Hence inplace.

- IntwPrep.MS December 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

@Alex, the solution is in place as the maximum size of the HashMap is 256 element for ascii coding. The 257th element has to be same. Hence, HashMap's size is constant.

- Anonymous December 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Remove duplicates from string..does that mean

abaaabbcdeee = abcd or = ababcde ?

If its second then its easy to do in O(n)

- confused_banda December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is the first one that was asked, not the second one.

- alex December 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Can use hash table, whenever a character is encountered put in hash table if not already present, otherwise return an indication character is already present

Keep two pointers, read pointer and write pointer. Readpointer moves always by one character ahead, write pointer moves ahead only when the hash table results in successful insert of character.

int hash_add(char c)
{
	/* bitmap is array of 127 bits or 16 bytes, each bit represents one ASCII
	 character, if set it is already present in hash table otherwise not */
	if( bitmap[ (c - 'a')/8 ] & (0x1 << (c-'a')%8) )
		return 1; /* already set */
	bitmap[ (c - 'a')/8 ] & (0x1 << (c-'a')%8);
	return 0;
}
unsigned int remove_duplicates(char *string)
{
	unsigned int rc = 0;
	char *rp = string;
	char *wp = string;
	while( *rp != '\0' )
	{
		if( hash_add( *rp ) == 0 )
		{
			*wp++ = *rp;
		}
		else
			rc++;
		rp++;
	}
	*wp = '\0'
	return rc;
}

Time complexity O(n), space complexity is O(1)

- confused_banda December 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

If the characters are s8 bits, you can use a 256 size boolean array as your O(1) space hashmap for an O(n) time algorithm.

- Anonymous December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think it formated my white space automatically while posting

If your string is "     Hello      World   "
Your output should be "Hello World"

- ish December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Ish, it is not about removing duplicate white spaces. It is about removing the duplicate characters.
From your example: Input: " Hello World "
Output: Helo Wrd"

- Srigopal Chitrapu January 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Sorry I posted to the wrong question. The one I posted is to remove duplicate white spaces in specific from a string

- Anonymous December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String is an immutable object. "in place" modification does not make sense to me

- Anonymous December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

eewe

- Anonymous December 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(N) algorithm: Keep count of number of spaces an unique character has to left shifted. Start with 0. Create hash map of 127 values
For each character,
1. If it is not yet seen, move it left by count. Add to hash map.
2. If it is duplicate, increment count.

- Anonymous December 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think using hash or boolean array voilates in place as it uses too much extra memory. Instead of using a boolean array, use a int variable and set its bits according to the Ascii value of the char you encounter. So you only very little extra space and hence it doesnt voilates inplace!

- Kesav December 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I faced the same question in the interview. I think what the meant was this

The array AMAZON would become AMZON\n. Just add a special character at the end to specify that you would have your result before that. In this case you just cant erase a string you have to copy the char 'Z' at index 2 and shift all the remaining characters by one.

This problem is little more involved than simple removal of duplicates.

- Pratik December 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming that string contain ASCII chars (array can be extended to 256 for extended ASCII), below solution in Java will take O(n) time:

public static String removeDupChars(String input) {
		if(input==null || input.length() == 0) {
			return input;
		}
		String newStr = "";
		int[] charSet = new int[128];
		for(char c : input.toCharArray()) {
			if(charSet[c] == 0) {
				newStr = newStr + c;
			}
			charSet[c]++;
		}
		return newStr;
	}

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

Idea to do it inplace is to swap the dupes to the end of the array and maintain a variable that tells you end of the unique values , result will be char [] from 0 to end. See code below :-

Note : string builder is just a syntactical sugar , we already have result in input array from 0 to end

public static string RemoveDupesInPlace(this string input)
        {
            bool[] present = new bool[255];
            int end = input.Length - 1;
            char temp;
            char[] inputArray = input.ToArray<char>();
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < inputArray.Length && i < end; i++)
            {
                if (present[inputArray[i] - 'a'])
                {
                    temp = inputArray[end];
                    inputArray[end] = inputArray[i];
                    inputArray[i] = temp;
                    end--;
                    i--;
                }
                else
                {
                    present[inputArray[i] - 'a'] = true;
                }
            }

            foreach (var item in inputArray.Take(end))
            {
                builder.Append(item);
            }

            return builder.ToString();

}

- Anchit.Koul December 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static char[] removeDups(char []dups) {

        int i = 0;

        for(int j = 1; j < dups.length;j++) {
            boolean flag = false;

            for(int k = 0;k <= i; k++) {
                if(dups[k] == dups[j]) {
                    flag = true;
                    break;
                }
            }

            if(flag == false) {
                i++;
                dups[i] = dups[j];
            }
        }

        return Arrays.copyOf(dups,i + 1);
    }

- glebstepanov1992 December 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class RemoveDup(
    val str: String) {

    def removedup(): String = {
        val a = new Array[Boolean](256)
        val sb = new StringBuffer
        str.foreach(c => {
            if (a(c.toInt) == false) {
              a(c.toInt) = true
              sb.append(c)
            }
        })
        sb.toString
    }
}

object RemoveDup {
    def main(args: Array[String]):Unit = {
        val inst = new RemoveDup("amazon")
        val after: String = inst.removedup
        println(after)
    }
}

- Annonymous December 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

use hashset and hashset buffer.
just check if the element is present in the hashset
if present{
put the element in to hashset
}
else
dont put.

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

/* assume ASCII */
int remove_duplicates(char *str)
{
    char *cp, *currentp;
    unsigned char map[32] = {0};

    for (currentp = str, cp = str; *cp; cp++)
    {
        if (!(map[*cp >> 3] & ( 1 << (*cp & 7))))
        {
            map[*cp >> 3] |= (1 << (*cp & 7));
            *currentp++ = *cp;
        }        
    }

    *currentp = '\0';

    return currentp - str;
}

- anon January 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

i am just going to help you out with logic:

first take the string in a variable

secondly use a loop construct to loop until the stringlength

use an if clause and compare the string character by character

if the character repeats two times go for else clause and increment the array of characters by +1 (this step eliminates the dual characters)

similarly for all
characters in an array and then print the array it display the series of character without duplicates .

Thus you can achieve it.
NOTE: take string as array of character as you take in C-lang.

Hope it was useful.
Thank U.-

- rupesh January 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

boolean check =false; //"";
		 
		 String word = "Hello World";
		 HashSet<Character>s = new HashSet<Character>();
		
		 String result = "";
		 for(int i = 0 ; i < word.length();++i)
		 {
			 check =s.add(word.charAt(i));
			 if(check==true)
			 {
				 result += word.charAt(i);
			 }
		 }
		 System.out.println(result);

- My algorithm, is it good or not !! April 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String dup(String word)
	{
 boolean check =false; //"";
		 
		 HashSet<Character>s = new HashSet<Character>();
		
		 String result = "";
		 for(int i = 0 ; i < word.length();++i)
		 {
			 check =s.add(word.charAt(i));
			
			  if(word.charAt(i)>='a'&&word.charAt(i)<='z')
			 {
				 char ch =  (char)((char)word.charAt(i)-'a'+'A');
				 check =s.add(ch);
				 if(check==true)
				 {
					 result += word.charAt(i);
				 }
			 }
			 else if(word.charAt(i)>='A'&&word.charAt(i)<='Z')
			 {
				 char ch =  (char)((char)word.charAt(i)-'A'+'a');
				 check =s.add(ch);
				 if(check==true)
				 {
					 result += word.charAt(i);
				 }
				 
			 }
			 else
			 {
				 if(check==true)
				 {
					 result += word.charAt(i);
				 }
			 }
			 
		 }
		 return result;
}

- waledsalah2005 April 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

O(n)

void rmDup(string &str) {
   set<char> s;
   for (int i = 0; i < str.size(); i++) {
       if (s.find(str[i]) == s.end()) {
           s.insert(str[i]);
       } else {
           str.erase(i,1);
       }
   }
}

- pretonesio December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

StringBuilder myNewString = new StringBuilder();
                for (int i = 0; i < str.Length; i++)
                {
                    if (i == 0 && str[i] == ' ')
                        continue;
                    if (i == str.Length - 1 && str[i] == ' ')
                        continue;
                    if (i > 0)
                    {
                        if (str[i] == ' ' && str[i - 1] == ' ')
                            continue;
                        else
                        {
                            
                            myNewString.Append(str[i]);
                        }
                    }
                }
                return myNewString.ToString();

suppose your string is " Hello World "
your output should be "Hello World"

- Ish December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

I think it is nor possible to do it in O(n) time complexity without extra space. In order to remove duplicates we have to keep track of elements which have been already processed or time complexity will be bigger cause multiple check of the same elements is required.

- thelineofcode December 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

a constant space is not an 'extra' space. so it can be done using a Boolean array of size 127 to remember encountered chars while traversal

- Anonymous December 20, 2013 | 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