2

I was working on this easy problem to practice basic Kotlin, and I ran into a stack overflow with the following code on the recursive return line:

class Solution {
    fun isPalindrome(s: String): Boolean {
        val cleaned = s.toLowerCase().replace(Regex("[^a-z0-9]"), "")
        tailrec fun isPalindrome(start: Int, end: Int): Boolean {
            if (start >= end) return true
            return cleaned[start] == cleaned[end] && isPalindrome(start+1, end-1)
        }
        return isPalindrome(0, cleaned.length-1)
    }
}

My understanding of tailrec is that it's supposed to convert my recursive function into an iterative one, which wouldn't be susceptible to this sort of crash. If I didn't implement tail recursion correctly, the compiler is supposed to issue an error.

Can someone explain to me why this crashes on large inputs, just like a standard recursive call would?

3
  • Not sure if short-circuiting counts as a tailcall. Commented Nov 10, 2019 at 3:01
  • Ah, and leetcode is suppressing warnings, and writing a tailrec function that isn't tail recursive only generates a warning, not an error. Commented Nov 10, 2019 at 3:08
  • 1
    I'm still curious were the difference is between the if(...) ... else tailCall() example in the docs and the ... && tailCall() in your example. As far as I can see there is no difference. Commented Nov 10, 2019 at 3:10

1 Answer 1

3

This behavior looks like a missing optimization of tail calls in short circuiting operators, where the fact that the last operand is being evaluated means that the expression result doesn't depend anymore on the previous operands.

Meanwhile you can rewrite your return statement as

return if (cleaned[start] != cleaned[end]) false else isPalindrome(start+1, end-1)

to get the same result + tail call optimization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.