LeetCode 28. Find the Index of the First Occurrence in a String

LeetCode Notes [49]: KMP Solution in Kotlin

John Lu
1 min readMar 11, 2023
© Warren Keelan

Problem

Approach: KMP (Knuth–Morris–Pratt) Algorithm

class Solution {
fun strStr(haystack: String, needle: String): Int {
val f = IntArray(needle.length) { 0 }
for (i in 1 until needle.length) {
var prev = f[i - 1]
while (prev > 0 && needle[i] != needle[prev]) {
prev = f[prev - 1]
}
if (needle[i] == needle[prev]) {
prev++
}
f[i] = prev
}

var i = 0
var j = 0
while (i < haystack.length) {
if (haystack[i] == needle[j]) {
i++
j++
if (j == needle.length) return i - needle.length
} else if (j > 0) {
j = f[j - 1]
} else {
i++
}
}
return -1
}
}

Complexity Analysis

  • Time complexity: O(n)
  • Space complexity: O(m)

--

--

John Lu

Android Developer. Deeply motivated by challenges and tends to be excited by breaking conventional ways of thinking and doing. He builds fun and creative apps.