Skip to content

Instantly share code, notes, and snippets.

@carolinemusyoka
Created October 30, 2021 20:00
Show Gist options
  • Save carolinemusyoka/e29f37a8a907079009e50e5a0fc5a432 to your computer and use it in GitHub Desktop.
Save carolinemusyoka/e29f37a8a907079009e50e5a0fc5a432 to your computer and use it in GitHub Desktop.
//Finding the length of the longest substring without repeating characters
//Solution
// Iterate through an array, evaluating if new substring should be the max substring
//Time complexity is O(n)..since we're iterating through an array once
//Space complexity is constant
class Solution {
fun lengthOfLongestSubstring(str: String): Int{
val map: HashMap<Char, Int> = hashMapOf()
var max = 0
// last repeat of any character
var lastRepeat = -1
str.forEachIndexed{j, value ->
var lOccur = map.get(value)
if(lOccur != null){
lastRepeat = maxOf(lastRepeat, lOccur)
}
max = maxOf(max, j - lastRepeat)
map.put(value, j)
}
return max
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment