0

Recently, I had to implement the following algorithm (similarly). Code in Kotlin:

fun solution(keyword: String, lyric: String): Boolean {
        val lyricWords = music.split(" ") 
        var index = 0
        for (word in lyricWords) {
          for (c in word) {
            if (c == keyword[index]) {
              index++
              break
            }
            if (index == word.size) return true
        }
        return false
 }

My intuition to the runtime analysis, given n to be the length of lyric and m the length of keyword:

  1. O(n) for the split operation, since it should scan the entire string looking for spaces.
  2. Roughly O(n) for the second for-loop, since it would iterate through all the characters for every word in the worst case.
  3. O(m) for the internal for-loop over all characters in keyword.
  4. Overall, should that take under O(n+m)?

What would be the time complexity for the above function?

kaneda
  • 101
  • 3

1 Answers1

1

For loop inside For loop indicates multiplication of time complexity parts.

For loop following for loop indicates addition of time complexity parts.

So I'd expect: $O(mn)$

That is to say. You doing $O(m)$, $n$ number of times. Thus $O(mn)$.

clinux
  • 257
  • 1
  • 7