Longest Substring Without Repeating Characters
Medium strings · sliding-window
Description
Constraints
0 <= length <= 100000
Examples
Input: s = "abcabcbb"
Output: 3
"abc"
Hints (1)
- Expand a window; when a repeat appears, move the left edge past the previous occurrence.
Solutions
Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))
func lengthOfLongestSubstring(s string) int {
last := map[byte]int{}
start, best := 0, 0
for i := 0; i < len(s); i++ {
if j, ok := last[s[i]]; ok && j >= start {
start = j + 1
}
last[s[i]] = i
if i-start+1 > best {
best = i - start + 1
}
}
return best
}
Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))
function lengthOfLongestSubstring(s) {
const last = new Map(); let start = 0, best = 0;
for (let i = 0; i < s.length; i++) {
if (last.has(s[i]) && last.get(s[i]) >= start) start = last.get(s[i]) + 1;
last.set(s[i], i);
best = Math.max(best, i - start + 1);
}
return best;
}
Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))
function lengthOfLongestSubstring($s) {
$last = []; $start = 0; $best = 0;
for ($i = 0; $i < strlen($s); $i++) {
$ch = $s[$i];
if (isset($last[$ch]) && $last[$ch] >= $start) { $start = $last[$ch] + 1; }
$last[$ch] = $i;
$best = max($best, $i - $start + 1);
}
return $best;
}
Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))
def lengthOfLongestSubstring(s):
last, start, best = {}, 0, 0
for i, ch in enumerate(s):
if ch in last and last[ch] >= start:
start = last[ch] + 1
last[ch] = i
best = max(best, i - start + 1)
return best
Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))
function lengthOfLongestSubstring(s: string): number {
const last = new Map<string, number>(); let start = 0, best = 0;
for (let i = 0; i < s.length; i++) {
if (last.has(s[i]) && last.get(s[i])! >= start) start = last.get(s[i])! + 1;
last.set(s[i], i);
best = Math.max(best, i - start + 1);
}
return best;
}
Create a free account to submit solutions, track progress and save problems.
Create account