Count the occurrence of a word in an incoming stream of characters

Viewed 1812

I was asked this question during an interview and although I am good in DS&Algo but this one I was not able to solve. This is an interesting question anyways so posting it.

Problem: You have an incoming stream of characters and you need to count the occurrences of a word. You have only one API to read from the stream which is stream.next_char() which return "\0" if there is none.

int count_occurrences(Stream stream, String word) {
// you have only one function provided from Stream class that you can use to 
// read one char at a time, no length/size etc.
// stream.next_char() - return "\0" if end
}

Input: "aabckjhabcc" Word: "abc" Output: 2

5 Answers
Related