I finished LeetCode 05 with simplified (for ease of implementation) Manacher's algorithm. IMHO it should keeps \$\mathcal{O}(n)\$ time and space complexity. However, LeetCode's benchmark ranked my solution as worst 5% and 30%. What causes such poor performance (time and space)? Can anybody help me diagnose where it went wrong?
Description:
Given a string s, return the longest palindromic substring in s.
Example:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Code:
data class LimitInfo(var center: Int, var rightMost: Int)
class Solution {
fun longestPalindrome(s: String): String {
val newS = s.fold("#") { acc, c -> "$acc$c#" }
val radii = MutableList(newS.length) { 0 }
val limitInfo = LimitInfo(0, 0)
fun symRadius(center: Int, checkedRadius: Int): Int {
var radius = checkedRadius + 1
while (newS.getOrNull(center - radius)?.equals(newS.getOrNull(center + radius)) == true) radius += 1
return radius - 1
}
newS.indices.forEach { center ->
val space = limitInfo.rightMost - center
val checkedRadius = when {
space < 0 -> 0
else -> minOf(radii[limitInfo.center * 2 - center], space)
}
val radius = symRadius(center, checkedRadius)
radii[center] = radius
if (center + radius > limitInfo.rightMost) {
limitInfo.rightMost = center + radius
limitInfo.center = center
}
}
val res = radii.withIndex().maxBy { it.value }!!.let { (loc, radius) ->
newS.slice(loc - radius..loc + radius)
}.filterIndexed { index, _ -> index % 2 == 1 }
return res
}
}