Occurrences After Bigram

Another easy one with a straightforward answer.

class Solution {
    fun findOcurrences(text: String, first: String, second: String): Array<String> {
        val words = text.split(" ")
        val output = mutableListOf<String>()
        for(i in 0 until words.size){
            if(i < words.size - 2 && words[i] == first && words[i + 1] == second){
                val third = words[i + 2]
                output.add(third)
            }
        }
        
        return output.toTypedArray()
    }
}
Runtime: 148 ms, faster than 90.91% of Kotlin online submissions for Occurrences After Bigram.
Memory Usage: 33 MB, less than 100.00% of Kotlin online submissions for Occurrences After Bigram.

The idea is to split the text by space and check if two consecutive words are equal to first and second respectively. Also, we want to make sure that our i will not exceed the size of words so we need to add the condition i < words.size - 2

comments powered by Disqus