Created
October 30, 2021 20:00
-
-
Save carolinemusyoka/e29f37a8a907079009e50e5a0fc5a432 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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