Interview Question for SDE-2s


Country: United States
Interview Type: In-Person




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

public static void main (String args[]) {
       // read input
       Scanner s = new Scanner (System.in);
       String input = s.nextLine();
       input = input.trim ();
       // core logic
       int count = 0;
       char prevChar = ' ';
       for (char c : input.toCharArray()) {
           if (prevChar != ' ' && c == ' ')
            count++;
            prevChar = c;
       }
       System.out.println ("Total words: " + ++count);
   }

- Dj January 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

will not work if the whole string is in 1 line, you cannot input 5GB string in 1 go

- anamika June 02, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Read the string and count the ' ' characters:

public static int countSpaceDelimSubstrings(String str){
	return countDelimSubstrings(str, ' ');
}

public static int countDelimSubstrings(String str, char delim){
	if(str == null){
		throw new NullPointerException("\"str\" may not be null");
	}
	int count = 0;
	boolean lastWasDelim = true;
	for(char c : str.toCharArray()){
		if(c != delim){
			if(lastWasDelim){
				count++;
				lastWasDelim = false;
			}
		}
		else{
			lastWasDelim = true;
		}
	}
	return count;
}

edits:
Changes some semantic errors that do not affect the logic

- zortlord December 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How will you handle the big size string chunks? Remember that the input data is very bulky....

- Jai December 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Also, the above code will fail when we have multiple spaces line a<space><space>b.

- Vikas December 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Vikas:
Barring a few unrelated semantic errors, the code operates correctly. I've run the code with the input 'a bbbbb c ddddd' and it correctly returned 4.
As to those semantic changes:
I changed line 2 from:

return countDelimChars(str, ' ');

to

return countDelimSubstrings(str, ' ');

and

for(char c : str.getChars()){

to

for(char c : str.toCharArray()){

- zortlord December 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Couldn't you just do it like this?

public static int countWords(String s) {
    String[] words = s.split(" ");
    return words.length;
}

Or am I misunderstanding something?

- daasq December 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

yes you are right except for the major 5 GB data, the idea is to use the stream reader like BufferedReader or something like that, you don't load everything into the main memory and load line or line or chunks of data and apply this logic. The assumption each line is self contained i.e. it does not have any dependencies on other lines..

- naren December 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Oh, got it. I didn't really read the question properly, thanks for pointing it out

- daasq December 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Precisely when a lazy language is awesome

countWords :: [Char] -> Int
countWords = foldl f 0
    where 
      f :: Int -> Char -> Int 
      f v ' ' = v + 1
      f v _ = v

- Anonymous December 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

should be foldl'

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

public class array_space_string {
public static void main(String []ar)
{

String a ="aagdsg" ;
int count =1;

for(int i = 0; i < a.length(); i++) {
if(Character.isWhitespace(a.charAt(i)) == true)
{
count++;

}

}


System.out.println("Number of words"+ count);

}

}

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

public static int count(String str){
     //covert str to a char Array
     char [] array = str.toCharArray();
     
     // Iterate through char array from array[0] to a[length-1] packing up
     // words in an arrayList as you go
     int beginIndex =0;
     //check if the first character is a delimiter or a "normal" character
     if (array[beginIndex] == ' '){
       //search for first 'normal' character
       while(array[beginIndex] == ' ') beginIndex++;
     }//
     ArrayList<String> words = new ArrayList<String>();
     String word = null;
     int i = beginIndex +1;
     
     while(i <array.length){
         if( array[i] == ' '){
        word = str.substring(beginIndex, i);
        words.add(word);       
        while(array[i] == ' ')
          i++;
        beginIndex = i;
        }//if
       i++;
     }//while
     word = str.substring(beginIndex, str.length());
     words.add(word);
     //return size of arraylist
     return words.size();
   }//count(String)

- Ghana_boy December 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

public class WordCount{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String s = "Hi Hello How are you kdfngndfgkjnffjkdjng sa d d d";
int len= s.length();
int count =0;
int index = 0;
for(int i=0;i<len;++i){

char c = s.charAt(index);
if(s.charAt(i)==' '){
index = index+1;
}

}
System.out.println(index+1);
}

}

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

declare variable empty_string=0;
Read each char from file and check whether it is " " .

if(read_charector()==" ") empty_string++;

after reading all the data o/p "empty_string + 1 ".

- kavetiraviteja1992 January 11, 2015 | 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