Microsoft Interview Question for Software Engineer in Tests


Country: India
Interview Type: Written Test




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

In python

"""
	write a sample code to find no of 'a' words in a sentence? 
	Eg: If a sentence is given as "I found an apple in a tree." 
	The output is : 1 (not 2) 
	We have to count no of words.

	loop all words 
	if it includes 'a' and its count more than 2 then increment count 
"""
def howManyA(sentence):
	count = 0
	for w in sentence.split( ):
		#if word has char more than 2, it's a word
		if len(w) > 2:
			for c in w:
				#char has 'a' than increment count and jump other word
				if c == 'a':
					count += 1
					break
	return count

print howManyA("I found an apple in a tree.")

- turan.emre June 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why thinking so hard?

HERE IS THE CONCEPT:


int FindNumOfA(char* sentence)
{
int cnt = 0;

if(tolower(sentence[0]) == 'a' && (sentence[1] == ' ' || sentence[1] == '\0')){
cnt ++;
}

int i = 1;

while( sentence[i] != '\0' ){
if( tolower(sentence[i]) == 'a'){
if(sentence[i - 1] == ' ' && sentence[i+1] == ' '){
cnt ++;
}
}

i++;
}

return cnt;
}


OUTPUT:

Eg: If a sentence is given as "I found an apple in a tree."
The output is : 1 (not 2)

- Priya September 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl -w

use strict;

my $sentence = <>;

my @words = split / /,$sentence;
my $count = 0;
foreach(@words)
{
$count++ if(/^a$/);
}

print "The output is:","$count\n";

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

I think we can just take the string as the input..... using String.split(" a ") , we get an array of size n, then there are (n-1) occurrences of "a"

- Fr0D0 June 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

good one :)

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

As the example, "I found an apple in a tree", your approach will return 3; but the expected answer is 1.

- this doesn't work June 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

sites.google.com/site/spaceofjameschen/home/sort-and-search/find-no-of-a-words-in-a-sentence----microsoft

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

int NumA(char *s)
{
char *length=s+strlen(s);
int flag=0,count=0,len=0;
char *b;
while(s<length)
{
if(*s!=' ')
{
b=s;
while(s<length && *s!=' ')
{
if(*s=='a')
{
flag=1;
}
len++;
s++;
}
if(flag==1 && len>2)
{count++;
flag=0;
len=0;
}
else if(flag==1)
{
flag=0;
}
}
}
return count;
}

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

Complexity O(string_length)

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

String str="I found an apple in a tree";
String[] articles={"a","an","the"};
String[] inputString=str.split(" ");
char inputChar='a';
int wordCnt=0;
for(String s: inputString){
if(!s.equalsIgnoreCase(articles[0])&&
!s.equalsIgnoreCase(articles[1])&&
!s.equalsIgnoreCase(articles[2])){
if(s.length()>1){
for(int i=0;i<s.length();i++){
if(inputChar==s.charAt(i)){
wordCnt+=1;
break;
}
}
}
}
}
System.out.println("word count:"+wordCnt);

This works.

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

String str="I found an apple in a tree";
String[] articles={"a","an","the"};
String[] inputString=str.split(" ");
char inputChar='a';
int wordCnt=0;
for(String s: inputString){
if(!s.equalsIgnoreCase(articles[0])&&
!s.equalsIgnoreCase(articles[1])&&
!s.equalsIgnoreCase(articles[2])){
if(s.length()>1){
for(int i=0;i<s.length();i++){
if(inputChar==s.charAt(i)){
wordCnt+=1;
break;
}
}
}
}
}
System.out.println("word count:"+wordCnt);

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

import math

s = raw_input()

words = s.split()
res=0
for i in range(0,len(words)):
if words[i]=="a":
res+=1
print res

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

I would suggest to use a window to processing the sentence plus a running count.

1. define 3 variable for the window and a pointer, say c0, c1, c2 and p. initialize them to -1.
2. start 1st character, p=1 and assign c2=s[p] and c1=s[p-1] and c0 = s[p-2] make sure the indexes are greater than zero before assignment.
3. if c1 equal to "a" and c0 = -1 or non-character and c2= -1 or non-charater, then add 1 to running count, and increase p by 3 and go back step 2.
4. if c1 not equal to "a" and c1 is character
a. and if c2 is non-character, then increase p by 2 and go back step 2.
b. otherwise, increase p by 3 and go back step 2.
5. do this until end of the sentence

please share and help to verify my solution. thx.

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

Aside from the normal case " a ", you also need to check for the boundary cases which include when the "a" is in the beginning of the string, the only letter in the string and at the end. This is a possible solution:

#include <iostream>
#include <string>

using namespace std;

int numWords(const string & word)
{
    int result = 0;
    if (word.at(0) == 'a' && word.size() == 1)
           return 1;
    for (int i = 0; i < word.size() - 1; ++i)
    {
        if (i == 0 && word.at(i) == 'a' && word.at(i + 1) == ' ')
            ++result;
        else if (i == word.size() - 2 && word.at(i) == ' ' && word.at(i + 1) == 'a')
            ++result;
        else if (word.at(i) == ' ' && word.at(i + 1) == 'a' && word.at(i + 2) == ' ')
            ++result;
        
    }
    return result;
}

int main()
{
    string word = "a How are you this is a test of a possible input a";
    cout << numWords(word) << endl;
    return 0;
}

The output in this case is 4

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

int countOfCharInString(const char str[], char aChar) {
int count = 0;
const char *p = str;
while (*p) {
if (*p == aChar ) {
if ((p == str || *(p-1) == ' ') && (!*(p+1) || *(p+1)==' ')) {
count++;
}
}
p++;
}
return count;
}

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

I wrote this in 10 seconds max. Sharing it via CodeBunk codebunk.com/bunk#-Ix32gaWuvvRpliFmpeA

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

class Program
    {
        public static int FindWordsContainingLetter(string sentence, char chr)
        {
            char[] sentArray = sentence.ToCharArray();

            int j =0;
            int cnt = 0;
            for (int i = 0; i < sentArray.Length; i++)
            {
                if (sentArray[i] != ' ')
                {
                    i++;
                }
                else if (sentArray[i] == ' ' && i - j > 1) //ignore single letters
                {
                    if (FindCharHelper(sentArray, j, i - 1, chr)) //i is sitting at space so decrement before passing
                    {
                        cnt++;
                    }
                }
            }

            return cnt;
        }

        public static bool FindCharHelper(char[] wordArray, int strt, int end, char chr)
        {
            bool found = false;
            for (int i = strt; i < end; i++)
            {
                if (wordArray[i] == chr)
                {
                    found = true;
                    break;
                }
            }

            return found;
        }

        static void Main(string[] args)
        {
            FindWordsContainingLetter("Does this string contain words with letter i", 'i');
        }
    }
}

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

public static int countAWords(String st) {
String[] strarr=st.split("\\s");
int count=0;
for(int i=0;i<strarr.length;i++) {
if(strarr[i].equalsIgnoreCase("a")) {
count++;
}
else {
continue;
}
}
return count;
}

- Apurva Shah July 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think by splitting the string by space we will get all the words and then just compare "a" with every word in the string array and return count.

- Apurva Shah July 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can separate the words and then check if its an 'a' word. We will have to parse the sentence atleast once.
public static String CountAs(String words) {
char[] letters = words.toCharArray();
int start = 0;
int end = 0;
int count = 0;
while (end < letters.length) {
if ((letters[end] == ' ' || letters[end] == letters.length - 1)) {
if (chkForA(letters,start,end-1)) {
count++;
start = end + 1;

} else {
start = end + 1;

}

}
end++;
}

if (chkForA(letters,start,end-1)) {
count++;
}
return count;
}

private static boolean chkForA(char[] letters, int start, int i) {
if((start == i) && letters[start] == 'a')
return true;
else
return false;
}

- Mz July 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Takes the sentence and the searched word (key) and returns the count of the key.

public int findFrequency(String sentence, String key) {		
	int count = 0;

	for (String word: sentence.split("\\W+")) {
		if (key.equals(key)) count++;
	}

	return count;
}

- oOZz June 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 votes

I dont think we are asked to find the frequency of a given word in a sentence here.
There needs to be a clarification on what is the meaning of number of 'a' words in the question.

- teli.vaibhav June 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It says "We have to count no of words.",i.e., the frequency of the words!

- oOZz June 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

@oOZz
your basic idea kind of works, but I think it is overkill to store all the words. Instead of a hashmap, just use one counter which increments whenever an 'a' word occurs. Also, not sure if 'a' word means 'a' or any word starting with 'a' and length > 1. If it is the latter, your idea doesnt work, since I dont think there is a way to find out which of the keys start with 'a' unless we use an iterator (which, btw is a hashset).

- anon June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

contd. from above comment. Looks like we are expected to find only strings with value "a". oOZz's approach will work.

- anon June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@anon it can't be the latter, because then you have "an" and "apple" and the output will be 2.

- oOZz June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It's saddening to see more and more posts with less than comprehensible descriptions of problems. This one almost takes the cake.

- liu425 June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

private static int HowManyA(string text)
        {
            if (String.IsNullOrEmpty(text))
                return 0;

            var word = "";
            var count = 0;
            foreach (var t in text)
            {
                if (t != ' ')               
                    word += t;              
                else 
                {
                    if (word == "a")
                        count++;
                    word = "";
                }
            }
            return count;

}

- fergy June 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@fergy This will not work if the word you're looking for is the last word

- oOZz June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

you are right. here is a modified version

private static int HowManyA(string text)
        {
            if (String.IsNullOrEmpty(text))
                return 0;

            var word = "";
            var count = 0;
            for (int i = 0; i < text.Length; i++)
            {
                if (i == text.Length-1 && text[i] == 'a' && word == "")
                {
                    count++;
                    continue;
                }
                var t = text[i];
                if (t != ' ')
                    word += t;
                else
                {
                    if (word == "a")
                        count++;
                    word = "";
                }
            }
            return count;
        }

- gifer81 June 08, 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