Valid Palindrome

Another easy problem and probably one of the most commonly asked questions in interviews.

class Solution {
    fun isPalindrome(s: String): Boolean {
        var low = 0
        var high = s.length - 1
        var input = s.toLowerCase()
        while(low < high){
            when {
                !Character.isLetterOrDigit(input[low]) -> low++ 
                !Character.isLetterOrDigit(input[high]) -> high--
                input[low] != input[high] -> return false
                else -> {
                    low++
                    high--
                }
            }            
        }
        
        return true
    }
}
Runtime: 184 ms, faster than 90.15% of Kotlin online submissions for Valid Palindrome.
Memory Usage: 34.9 MB, less than 100.00% of Kotlin online submissions for Valid Palindrome.

We will use two-pointer strategy where in we increase any of the pointers whenever we encounter an non-digit or letter character. Then as soon as we hit a non-matching letter or digit, then we return false immediately.

comments powered by Disqus