I am practicing coding questions on leetcode. I have been an OOP my whole career, and I am trying to wade into the dark abyss that is functional programming. So I am trying to do things purely functional, e.g. using recursion to try to get to the answer. The problem statement is this: Given a string, find the length of the longest substring without repeating characters.
Sorry for asking literally this leetcode question that everybody else is asking :D
I have coded up this solution -
class Solution {
fun lengthOfLongestSubstring(str: String): Int {
return when {
str.length == 1 -> 1
str.isEmpty() -> 0
else -> helper(str, 0, 1, 0)
}
}
private tailrec fun helper(str: String, leftIndex: Int, rightIndex: Int, max: Int): Int {
return when {
rightIndex >= str.length+1 -> max
rightIndex >= str.length && isDistinct(str.substring(leftIndex)) ->
helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
isDistinct(str.substring(leftIndex, rightIndex)) ->
helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
}
}
private fun isDistinct(substring: String): Boolean {
return substring.toList().distinct().size == substring.length
}
}
I have a couple specific questions - I am using the sliding window approach, is that appropriate in a functional setting? If not, what is a better approach functionally, speaking.
Is there redundancy in my recursion function that I can get rid of?
What things can I do to improve the legibility of the function? Clean code is always best!
What further steps can I take to optimize the solution? Currently this solution is only faster than 10% of other solutions (though those are likely imperative solutions)
Any other tips you can provide outside of the bounds of my question that can help would be awesome. I am also brand new to kotlin programming.
I don't necessarily hate this solution, but I'm sure it can be better. Please advise.