Longest Substring Without Repeating Characters
MediumStrings · Sliding windowO(n) time · O(k) space
The problem
Given a string, return the length of the longest substring with no repeated characters.
"abcabcbb" → 3 ("abc")
"bbbbb" → 1 ("b")
"pwwkew" → 3 ("wke")Stuck? Open one hint
Keep a window that is always valid. When a repeat arrives, where exactly must the left edge jump to?
Show the worked solution
This is the sliding-window template. Keep a window [left, right] that never contains a duplicate, and a map of character → last index.
Move right forward. If the character was seen inside the current window, move left to one past its last position — not one step at a time, straight there. Record the window size at every step.
The trap is forgetting "inside the current window": a character seen long before left is harmless, so guard with last >= left.
fun lengthOfLongestSubstring(s: String): Int {
val lastIndex = HashMap<Char, Int>()
var left = 0
var best = 0
for (right in s.indices) {
val c = s[right]
val last = lastIndex[c]
if (last != null && last >= left) left = last + 1
lastIndex[c] = right
best = maxOf(best, right - left + 1)
}
return best
}O(n) time · O(k) space
